【发布时间】:2014-02-01 00:44:11
【问题描述】:
我的问题是关于 C++ 中的继承和多态性。
class Base
{
public:
virtual void f() { cout << "Base::f()" << endl; }
void f(string s) { cout << "Base::f(string)" << endl; }
};
class Derivate1: public Base
{
public:
void f() { cout << "Derivate1::f()" << endl; }
void f(int i) { cout << "Derivate1::f(int)" <<endl; }
};
class Derivate2: public Base
{
public:
void f() { cout << "Derivate2::f()" << endl; }
void f(char c) { cout << "Derivate2::f(char)" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
//with base pointers
Derivate1 d1;
Derivate2 d2;
Base *b1 = &d1;
Base *b2 = &d2;
b1->f(); //output: Derivate1::f() ok.
b1->f("string"); //output: Base::f(string) ok.
b1->f(1); //error !
b2->f(); //output: Derivate2::f() ok.
b2->f("string"); //output: Base::f(string) ok.
b2->f('c'); //error !
//with direct derivate object
d1.f(); //output: Derivate1::f() ok.
d1.f("string"); //error !
d1.f(1); //output: Derivate1::f(int) ok.
d2.f(); //output: Derivate2::f() ok.
d2.f("string"); //error !
d2.f('c'); //output: Derivate2::f(char) ok.
return 0;
}
如果我想在派生对象中使用可访问的基类中的重新定义函数,我必须做什么?我不想在派生类中使用Base::f;。
【问题讨论】:
标签: c++ inheritance polymorphism