这是我的代码
class B {
public:
virtual void insert(int t, int p) = 0;
void insert(int t) {
insert(t, 0);
}
};
class D : public B {
public:
void insert(int t, int p) { }
};
int main() {
D d;
d.insert(1);
}
Run Code Online (Sandbox Code Playgroud)
哪个不会编译.当然,如果我在主要中说dB :: insert(1),但为什么这是不正确的呢?谢谢.
这是因为在这种情况下,基类功能不包含在重载决策中.类似的情况是在内部作用域中声明的函数 - 它们不会重载在外部作用域中声明的函数(参见下面的示例).您可以想象派生类作用域嵌套在基类作用域内.
一旦编译器找到D::insert候选者,它将不会在基类中进一步查看.如果没有,D::insert那么编译器将查看基类insert以便调用方法.您可以通过insert从基类引入函数名来解决此问题:
using B::insert;
Run Code Online (Sandbox Code Playgroud)
这将引入B::insert派生类中的所有重载函数.或者如您所说,您可以使用以下方法显式调用基类方法:
d.B::insert(1)
Run Code Online (Sandbox Code Playgroud)
有关重载如何在其他上下文中以相同方式工作的示例代码:
namespace Outer {
void foo(double d) {
std::cout << "Outer::foo(double d)\n";
}
namespace Inner {
//using Outer::foo; // uncomment to see "Outer::foo(double d)" in output
void foo(int n) {
std::cout << "Inner::foo(int n)\n";
}
void callMe() {
foo(1.1);
}
}
}
int main() {
Outer::Inner::callMe(); // Outputes: Inner::foo(int n)
}
Run Code Online (Sandbox Code Playgroud)
要么:
void foo(std::string s) {
std::cout << "foo(std::string s)\n";
}
void foo(double d) {
std::cout << "foo(double d)\n";
}
void foo(int n) {
std::cout << "foo(int n)\n";
}
int main() {
void foo(int d); // comment out to see foo(double d) in output
foo(1.1); // outputs: "foo(int n)", foo(double d) is hidden
//foo("hello"); // ups, it wont compile - name lookup in c++ happens before type checking
// commenting out `void foo(int d);` above will fix this.
}
Run Code Online (Sandbox Code Playgroud)
小智 0
我很确定这是因为您在 D 中重新定义了函数“insert”,这是被调用的函数。类“D”中的函数“insert”需要两个参数,而不是一个。通过执行 dB::insert(1),您可以在 B 中调用“insert”。
| 归档时间: |
|
| 查看次数: |
856 次 |
| 最近记录: |