c++ - 基类和派生类 C++

标签 c++ class inheritance

几天前,我想深入了解 C++ 世界。我正在研究基类和派生类的概念。有人可以解释以下两个代码片段的细微差别吗?

class A
{
    private:
    virtual int GetValue() { return 10; }

    public:
    int Calculate() { return GetValue()*1.5; }
};

class B: public A
{
    private:
    virtual int GetValue() { return 20; }
};

int main()
{
    B b;
    std::cout << b.Calculate() << std::endl;

    return 0;
}

The output is 30 but 15 was expected

class A
{
    private:
    int m_data;

    public:
    A(): m_data(GetValue()) {}
    int Calculate() { return m_data*1.5; }
    virtual int GetValue() { return 10; }
};

class B: public A
{
    public:
    virtual int GetValue() { return 20; }
};

int main()
{
    B b; A* ap;
    ap=&b; 
    std::cout << ap->Calculate() << std::endl;

    return 0;
}

The output is 15 but 30 was expected

Can someone explain and help me understand the reasoning? Something is wrong with my thinking on this concept, but I am unable to figure it out.

最佳答案

第一种情况:

这是微不足道的。您有 B 的实例化实例,并且您计算 return GetValue() * 1.5; 时使用 B::GetValue()已在基类中将 GetValue() 标记为 virtual。因此 20 * 1.5 被评估。

第二种情况:

不是那么琐碎。您在基本成员初始化程序中调用 GetValue() 来为 m_data 设置一个值。标准 C++ 规定在这种情况下将调用基类 GetValue() 方法。 (非正式地认为这是由于类 B 在类 A 完全构造之前未被构造)。因此 10 * 1.5 被评估。有趣的是,如果 GetValue()纯虚拟,那么程序的行为将是未定义


引用:Why a virtual call to a pure virtual function from a constructor is UB and a call to a non-pure virtual function is allowed by the Standard?

关于c++ - 基类和派生类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42908712/

相关文章:

c++ - 使用 opengl c++ 的天空盒问题

javascript - 从字符串名称动态创建 JavaScript 函数

class - 用基类初始化派生类

c++ - 定义基类的静态变量

c++ - 为什么使用指针会降低性能

c++:为什么不能使用模板来推断容器和元素类型?

c++ - C++结构数组的新顺序

c# - 采用接口(interface)+抽象类的继承设计。好的做法?

c++ - 在编译时用基于模板的长度初始化一个 const 数组

java - 可以使用 switch 语句来确定对象的类吗?