继承、保护.疯狂的编译器

inheritance, protected. Crazy compiler

本文关键字:编译器 疯狂 保护 继承      更新时间:2023-10-16
class Rectangle{
public:
    Rectangle(double l=0.0, double w =0.0) : length(l), width(w){}
    double getLength() {return lenght;}
    double getWidth() { return width;}
    virtual double Area() { return length * height;}
protected:
    double length, width;
};
class Box : public Rectangle{
    public:
    // ERROR: compiler error on the next line:
    Box(double l, double w, double h) : length(l), width(w), height(h){}
    double getHeight() {return height;}
    double Volume();
    double Area(){
        return 6*length * width;
    }
    private:
    double height;
};

在标记行

上出现编译错误
Box(double l, double w, double h) : length(l), width(w), height(h){}

编译器报错class Box没有任何名为width的字段。有什么问题吗?也许length在基类中受到保护?

首先你一开始就打错字了。你应该修改:

double getLength() {return lenght;}

:

double getLength() {return length;}
//                             ^^

其次,在您的Rectangle类中,您正在使用您未在类中声明的height标识符:

virtual double Area() { return length * height;}

最后,使用Rectangle构造函数初始化其成员。所以不是:

Box(double l, double w, double h) : length(l), width(w), height(h){}

使用:

Box(double l, double w, double h) : Rectangle(l, w), height(h){}

如果你修复了每一个错误,你的程序将会编译得很好。

必须调用Rectangle构造函数,而不是Rectangles成员的构造函数!

不能在初始化列表中初始化基类的成员。使用这个

Box(double l, double w, double h) : Rectangle(l,w), height(h){}