我有两个关于虚拟方法的问题。
首先:
class Parent
{
public:
virtual void SHOW(int x = 5) { cout << "PARENT " << x << endl; }
};
class Child : public Parent
{
public:
virtual void SHOW(int y = 10) { cout << "CHILD " << y << endl; }
};
int main()
{
Child Y;
Parent* P = &Y;
P->SHOW();
getch();
return 0;
}
我认为 tt 应该是 CHILD 10 但结果是 CHILD 5
还有一个:
class Parent
{
public:
virtual void SHOW() { cout << "PARENT" << endl; }
};
class Child : public Parent
{
private:
virtual void SHOW() { cout << "CHILD" << endl; }
};
int main()
{
Child Y;
Parent* P = &Y;
P->SHOW();
getch();
return 0;
}
它将在屏幕上显示CHILD。我不知道如何从外部调用私有(private)方法?
谢谢。我正在学习英语所以.. :)
最佳答案
1) C++ 标准说
A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
§8.3.6/10
2) Overriding public virtual functions with private functions in C++
关于C++类和虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895156/