c++ - 使用类的构造函数时出错
问题描述
在构造函数中使用初始化列表时出现 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;
};
解决方案
内联评论:
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;
};
推荐阅读
- c - 如何使用 espconn 捕获 HTTPS 请求?
- javascript - 类型“TElement”上不存在属性“已检查”
- java - 将证书添加到 JVM 密钥库后,Tomcat 无法找到请求目标的有效证书路径
- javascript - 从包含许多文件的文件夹中反应本机动态导入图像
- java - 字符串“Switch Case”简单代码
- javascript - 单击Reach JS替换变量中的值
- json - Visual Studio Code:尝试添加对新语言/文件类型的支持时未检测到注释
- ruby-on-rails - Geokit 是否使用默认的 google API 密钥?
- c - 不确定具有 posix 线程和 openMP 的并行程序的计时正确性
- jms - javax.naming.NoInitialContextException:无法找到 InitialContextFactory com.tibco.tibjms.naming.TibjmsInitialContextFactory