首先,下面的代码不能在 Visual C++ 中运行,但可以在 Bloodshed 中运行
输出是 0 ,但是 acc.对我来说应该是 1 ;谁能解释一下这个
#include<iostream>
using namespace std;
class shape
{
public:
virtual void print() const =0;
virtual double area() { return 0.0;}
};
class point : public shape
{
int x;
int y;
public :
point(int a=11, int b=11)
{
x=a;
shape *s;
s=this;
cout<<s->area();
y=b;
}
double area()const {return 1.0;}
void print() const
{
cout<<"\nPoint\n";
cout<<x<<"\t"<<y;
}
};
int main()
{
point p(1,2);
return 0;
}
最佳答案
您的代码中有一个微妙的缺陷:
double area()const {return 1.0;}
基类的 area()
方法未声明为 const
。因此 point::area 不是虚拟方法。要么声明 shape::area
const
,要么从 point::area
中删除 const,它将按预期工作。
关于c++ - C++ 中带有虚函数调用的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1995009/