C++类和虚方法

标签 c++ class virtual private

我有两个关于虚拟方法的问题。

首先:

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/

相关文章:

c++ - 在 C++ 中关联 3 个事物的最佳方式

c# - 一个类的一个属性指的是同一个类。如何管理实例

javascript - 使用 Javascript 函数定义 html 类

c++ - Windows XP 套接字错误与 recv()

c++ - 堆栈上的竞争条件

c++ - 无效使用不完整类型 'class...'

c++ - 密封类实现查询

html - 嵌套在 ng-virtual-repeat 中的 Ng-Repeat 不起作用

c++ - operator<< 内部的虚方法调用

c++ - vector<T> 的内存结构