关于从派生的基类中实现的 C++ 调用虚函数的问题 class
Question about C++ call virtual function implemented in base from derived class
下面的代码有什么问题?
struct A {
virtual int hash() const = 0;
virtual int hash(int x) const = 0;
};
struct B : public A {
int hash() const final {
return 10;
};
int hash(int x) const override {
return 10;
};
};
struct C : public B {
int hash(int x) const override {
return x;
}
};
#include <iostream>
int main() {
C a;
std::cout << a.hash() << std::endl;
std::cout << a.hash(20) << std::endl;
return 0;
}
我遇到编译错误并显示以下错误消息
xx.cc:26:23: error: too few arguments to function call, single argument 'x' was
not specified
std::cout << a.hash() << std::endl;
~~~~~~ ^
xx.cc:17:3: note: 'hash' declared here
int hash(int x) const override {
^
1 error generated.
是的,您必须在派生的 class 中重新定义重载。
struct C : public B {
int hash(int x) const override {
return x;
}
int hash() const override {
return B::hash();
}
};
或者通过引用 B
调用
int main() {
C a;
B& b = a;
std::cout << b.hash() << std::endl;
std::cout << b.hash(20) << std::endl;
return 0;
}
这是姓名隐藏问题。根据name lookup,
的规则
(强调我的)
name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
所以 C::hash
从基础 class 中隐藏了名称。
您可以应用using
将名称引入class C
范围。
struct C : public B {
using B::hash;
int hash(int x) const override {
return x;
}
};
下面的代码有什么问题?
struct A {
virtual int hash() const = 0;
virtual int hash(int x) const = 0;
};
struct B : public A {
int hash() const final {
return 10;
};
int hash(int x) const override {
return 10;
};
};
struct C : public B {
int hash(int x) const override {
return x;
}
};
#include <iostream>
int main() {
C a;
std::cout << a.hash() << std::endl;
std::cout << a.hash(20) << std::endl;
return 0;
}
我遇到编译错误并显示以下错误消息
xx.cc:26:23: error: too few arguments to function call, single argument 'x' was
not specified
std::cout << a.hash() << std::endl;
~~~~~~ ^
xx.cc:17:3: note: 'hash' declared here
int hash(int x) const override {
^
1 error generated.
是的,您必须在派生的 class 中重新定义重载。
struct C : public B {
int hash(int x) const override {
return x;
}
int hash() const override {
return B::hash();
}
};
或者通过引用 B
调用int main() {
C a;
B& b = a;
std::cout << b.hash() << std::endl;
std::cout << b.hash(20) << std::endl;
return 0;
}
这是姓名隐藏问题。根据name lookup,
的规则(强调我的)
name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
所以 C::hash
从基础 class 中隐藏了名称。
您可以应用using
将名称引入class C
范围。
struct C : public B {
using B::hash;
int hash(int x) const override {
return x;
}
};