我无法构建一个派生类对象!谁能帮助我! [英] I can't build a derive class object!who can help me!

查看:60
本文介绍了我无法构建一个派生类对象!谁能帮助我!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
class CShape
{

private:
    char cType[20];
    float fArea;

public:

    CShape(){}
    CShape(char * cType_name , float fA) : fArea(fA) { std::strcpy(cType,cType_name); }
    virtual void print()
    {

        std::cout << "Type: " << cType << std::endl;
        std::cout << "Area: " << fArea << std::endl;

    }
    virtual float area() const = 0;

};

class CCircle : public CShape
{

private:
    float fRadius;

public:

    CCircle(){}
    CCircle (float fR=0 ) : CShape("CCircle",3.14*fR*fR) { fRadius=fR;}
    virtual void print ()
    {

        CShape::print();
        std::cout << "Radius: " << fRadius << std::endl;

    }

    float virtual area() { return 3.14*fRadius*fRadius; }


};


int main()
{

    CCircle cir(1);

}





以上是我的代码,系统提示CCircle是一个抽象类! />
我不知道为什么!谁可以帮助我!



The above is my code , the system prompt that CCircle is a abstract class!
I don''t know why! who can help me!

推荐答案

当覆盖虚拟方法时,你必须确保方法签名完全匹配(请参阅布莱登的评论)。改变来自

When overriding virtual methods you have to make sure that the method signatures exactly match (please see Brydon''s remark). Change from
Quote:

float virtual area(){return 3.14 * fRadius * fRadius; }

float virtual area() { return 3.14*fRadius*fRadius; }

to

to

virtual float area() const { return 3.14*fRadius*fRadius; }


从CCircle中的方法中取出 virtual 。请尝试覆盖



任何包含虚拟函数是定义抽象的。
Take the virtual off the methods in CCircle. Try override instead.

Any class that contains a virtual function is abstract by definition.


编译器不允许声明对象d,因为CCircle是一个抽象类;它从AB继承了纯虚函数f()。如果定义函数CCircle :: area(),编译器将允许声明对象d。



请注意,您可以从非抽象类派生抽象类,并且你可以使用纯虚函数覆盖非纯虚函数。



你可以做的是你可以创建一个指向该CCricle类的指针

ie,

CCricle * l_ptrcricle;

l_ptrcricle =新的CCricle; //你会给出错误
The compiler will not allow the declaration of object d because CCircle is an abstract class; it inherited the pure virtual function f()from AB. The compiler will allow the declaration of object d if you define function CCircle ::area().

Note that you can derive an abstract class from a nonabstract class, and you can override a non-pure virtual function with a pure virtual function.

what you can do is you can create a pointer to that CCricle class
i.e,
CCricle *l_ptrcricle;
l_ptrcricle= new CCricle;// will you give a error


这篇关于我无法构建一个派生类对象!谁能帮助我!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆