首页 > 解决方案 > 使用类的构造函数时出错

问题描述

在构造函数中使用初始化列表时出现 2 个错误。

第一个错误:“Shape 类不存在默认构造函数”

第二个错误:“成员 Shape::name 无法访问”我的代码:

class Shape
{
public:
    Shape(const std::string& name, const std::string& type): _name(name), _type(type){}

    virtual ~Shape();
private:
    std::string _name;
    std::string _type;
};
class Circle : public Shape
{
public:
    Circle(const Point& center, double radius, const std::string& type, const std::string& name) : 
        _center(center), _radius(radius), _type(type), _name(name) {}
    ~Circle();
protected:
    Point _center;
    int _radius;
};

标签: c++oopconstructor

解决方案


内联评论:

class Shape
{
public:
    Shape(const std::string& name, const std::string& type): _name(name), _type(type){}
    Shape() : Shape("", "") {} // default ctor, delegating
    virtual ~Shape() = default; // better if you don't want to enforce implementing
                                // a dtor in every subclass

protected: // lifted from private if you need direct access from Circle
    std::string _name;
    std::string _type;
};

class Circle : public Shape
{
public:
    Circle(const Point& center, double radius, const std::string& type, const std::string& name) : 
        Shape(name, type), // use constructor of Shape
        _center(center),
        _radius(radius)
    {}
    // ~Circle() {} // not needed if base is default
protected:
    Point _center;
    int _radius;
};

推荐阅读