gpt4 book ai didi

c++ - c++中带虚函数调用的构造函数

转载 作者:太空狗 更新时间:2023-10-29 21:30:44 25 4
gpt4 key购买 nike

首先,下面的代码在 visual c++ 中不起作用,但在流血中起作用

输出为 0 ,但符合。对我来说应该是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com