7

我是 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);

 }

我的意图是访问圆形区域值和圆形对象区域值。最后我写了函数 const Box& getBoxArea() const; 像这样:

  const Box& getBoxArea() const
  {
       return this->box;    
  }

结果我没有得到正确的值。我在这里想念什么?

4

2 回答 2

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)) { }
    ...
}
于 2013-10-14T08:10:27.660 回答
4

我建议编写一个根据输入字符串计算 的非成员函数,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);
}
于 2013-10-14T08:11:10.700 回答