在另一个类构造函数中初始化一个类对象

use*_*007 5 c++ class

我是C++的新手.好吧,我有box.cpp和circle.cpp文件.在我解释我的问题之前,我想给你他们的定义:

在box.cpp中

  class Box
  {
       private:
       int area;

       public:
       Box(int area);
       int getArea() const;

  }
Run Code Online (Sandbox Code Playgroud)

在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;  

   }
Run Code Online (Sandbox Code Playgroud)

现在你可以在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);

 }
Run Code Online (Sandbox Code Playgroud)

我的目的是访问Circle区域值和Circle对象区域值.最后我写了函数const Box&getBoxArea()const; 像这样:

  const Box& getBoxArea() const
  {
       return this->box;    
  }
Run Code Online (Sandbox Code Playgroud)

结果我得不到正确的值.我在这里错过了什么?

Lih*_*ihO 5

在构造函数中,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)) { }
    ...
}
Run Code Online (Sandbox Code Playgroud)


jua*_*nza 4

我建议编写一个非成员函数来int根据输入字符串计算 ,然后在Circle的构造函数初始化列表中使用它。

std::string foo(int area) { .... }
Run Code Online (Sandbox Code Playgroud)

然后

Circle :: Circle(int area, string str) : box(foo(str)) { .... }
Run Code Online (Sandbox Code Playgroud)

您只能初始化初始化列表中的非静态数据成员。一旦进入构造函数主体,一切都已为您初始化,您所能做的就是对数据成员进行修改。因此,如果有默认构造函数,则可以编译的代码的一种变体Box

Circle :: Circle(int area, string str) : area(area)
{
  // calculate int_str
  ....
  box = Box(int_str);
}
Run Code Online (Sandbox Code Playgroud)