几天前,我想深入了解 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()
是纯虚拟,那么程序的行为将是未定义。
关于c++ - 基类和派生类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42908712/