我是 C++ 新手。嗯,我有 box.cpp 和 Circle.cpp 文件。在解释我的问题之前,我想先给你解释一下它们的定义:
在盒子.cpp中
class Box
{
private:
int area;
public:
Box(int area);
int getArea() const;
}
在circle.cpp中
#include "box.h"
class Circle
{
private:
int area;
Box box;
public:
Circle(int area, string str);
int getArea() const;
const Box& getBoxArea() const;
}
现在,正如您在 Circle 类中看到的那样,我有一个整数值和 Box 对象。在 Circle 构造函数中,我可以轻松地将整数值分配给区域。
一个问题是我得到了一个字符串来将其分配给 Box 对象
所以我在 Circle 构造函数中所做的是:
Circle :: Circle(int area, string str)
{
this->area = area;
// here I convert string to an integer value
// Lets say int_str;
// And later I assign that int_str to Box object like this:
Box box(int_str);
}
我的目的是访问圆面积值和圆对象面积值。
最后我编写了函数 const Box& getBoxArea() const;像这样:
const Box& getBoxArea() const
{
return this->box;
}
结果我没有得到正确的值。我在这里缺少什么?
在构造函数中Circle
您正在尝试创建一个实例Box
,这已经太晚了,因为当构造函数的主体被执行时,Circle
应该已经建成。班级Box
要么需要默认构造函数,要么需要初始化box
在初始化列表中:
Box constructBoxFromStr(const std::string& str) {
int i;
...
return Box(i);
}
class Circle
{
private:
int area;
Box box;
public:
Circle(int area, string str)
: area(area), box(constructBoxFromStr(str)) { }
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)