因此,这个程序:
#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
,并且一切都按预期工作。
override
е…ій”®еӯ—пјҢзј–иҜ‘еҷЁдјҡе‘ҠиҜүдҪ жІЎжңүйҮҚеҶҷеҹәзұ»еҮҪж•°гҖӮ - WhiZTiM