C++标准规定禁止从构造函数或析构函数中调用纯虚函数.这是什么原因?标准为什么要设置这样的限制?
几天前,我想深入了解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;
}
Run Code Online (Sandbox Code Playgroud)
产量为30,但预计为15
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 …Run Code Online (Sandbox Code Playgroud)