基于派生类的C++调用虚函数的问题
以下代码有什么问题基于派生类的C++调用虚函数的问题,c++,inheritance,member-functions,name-lookup,name-hiding,C++,Inheritance,Member Functions,Name Lookup,Name Hiding,以下代码有什么问题 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
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.
是的,您必须在派生类中重新定义重载 结构C:公共B{ int hashint x const覆盖{ 返回x; } int哈希常量重写{ 返回B::hash; } }; 或者通过对B的引用调用 int main{ C a; B&B=a;
是的,您必须在派生类中重新定义重载 结构C:公共B{ int hashint x const覆盖{ 返回x; } int哈希常量重写{ 返回B::hash; } }; 或者通过对B的引用调用 int main{ C a; B&B=a;
std::cout这是名称隐藏问题。根据 重点矿山 名称查找按如下所述检查作用域,直到找到至少一个任何类型的声明,此时查找停止,不再检查其他作用域 所以C::hash对基类隐藏了名称 您可以使用将名称引入C类范围
这是名字隐藏的问题。根据 重点矿山 名称查找按如下所述检查作用域,直到找到至少一个任何类型的声明,此时查找停止,不再检查其他作用域 所以C::hash对基类隐藏了名称 您可以使用将名称引入C类范围
struct C : public B {
using B::hash;
int hash(int x) const override {
return x;
}
};