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

标签 c++ constructor virtual

首先,下面的代码不能在 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/

相关文章:

c++ - 如何在 C++11 的成员函数中实现多态函数?

c# - 设计指定构造函数

关于复制构造函数的 C++ OOP 程序问题?遗产

c# - 是否有不需要虚拟方法的.NET/C# 模拟框架

c++ - 将 LPTHREAD_START_ROUTINE 转换为 int

c++ - 如何使用指针从不同的函数访问局部变量?

c++ - 内存映射内存可能吗?

c++ - 不执行参数化基类构造函数就存在中间类

c++ - 我可以从派生类中排除基类成员吗?

c++ - 带有嵌入式结构和虚函数的段错误