[英]Initialize a class object inside the other class constructor
我是C ++的新手。 好吧,我有box.cpp和circle.cpp文件。 在我解释我的问题之前,我想给你他们的定义:
在box.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);
}
我的目的是访问Circle区域值和Circle对象区域值。 最后我写了函数const Box&getBoxArea()const; 像这样:
const Box& getBoxArea() const
{
return this->box;
}
结果我得不到正确的值。 我在这里错过了什么?
在Circle
构造函数中,您正在尝试创建Box
的实例,这已经太晚了,因为在构造函数的主体执行时, Circle
的成员已经构造。 Class 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)) { }
...
}
我建议编写一个非成员函数,根据输入字符串计算int
,然后在Circle
的构造函数初始化列表中使用它。
std::string foo(int area) { .... }
然后
Circle :: Circle(int area, string str) : box(foo(str)) { .... }
您只能初始化初始化列表中的非静态数据成员。 进入构造函数体后,所有内容都已为您初始化,您所能做的就是对数据成员执行修改。 所以如果Box
有一个默认的构造函数,你的代码的一个变种就是
Circle :: Circle(int area, string str) : area(area)
{
// calculate int_str
....
box = Box(int_str);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.