为什么这个程序:
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Costruttore Base" << endl; }
virtual void foo(int) { cout << "Base::foo(int)" << endl; }
virtual void bar(int) { cout << "Base::bar(int)" << endl; }
virtual void bar(double) { cout << "Base::bar(double)" << endl; }
virtual ~Base() { cout << "Distruttore Base" << endl; }
};
class Derived : public Base {
public:
Derived() { cout << "Costruttore Derived" << endl; }
void foo(int) { cout << "Derived::foo(int)" << endl; }
void bar(int) const { cout << "Derived::bar(int)" << endl; }
void bar(double) const { cout << "Derived::bar(double) const" << endl; }
~Derived() { cout << "Distruttore Derived" << endl; }
};
int main() {
Derived derived;
Base base;
Base& base_ref = base;
Base* base_ptr = &derived;
Derived* derived_ptr = &derived;
cout << "=== 1 ===" << endl;
base_ptr->foo(12.0);
base_ref.foo(7);
base_ptr->bar(1.0);
derived_ptr->bar(1.0);
derived.bar(2);
return 0;
}
在调用 base_ptr->bar(1.0);
中调用 Base::bar(double)
,而不是在 derived_ptr->bar(1.0 );
被称为 Derived::bar(double) const
。
我知道这是关于 const
关键字的,但我不明白为什么编译器会选择不同的重载函数。
如果我删除 const
关键字,一切都会按预期工作,在这两种情况下都会调用 Derived::bar
最佳答案
那是因为const
改变了函数的签名,所以它们是不同的。要么使基类和派生类都成为const
,要么一个都不会覆盖另一个。
关于C++ - 方法和重载中的 const 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716636/