Initialize a class object inside the other class c

2019-06-23 16:27发布

I am new to C++. Well I have box.cpp and circle.cpp files. Before I explain my problem I'd like to give you their definitions:

In box.cpp

  class Box
  {
       private:
       int area;

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

  }

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

   }

Now as you can see in the Circle class I have an integer value and Box object. And in Circle constructor I assign that integer values easily to area.

One problem is that I am given a string for assigning it to the Box object

So what I did inside the Circle constructor is that:

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

 }

My intention is to access both Circle area value and Circle object area value. And Finally I write the function const Box& getBoxArea() const; Like this:

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

And as a result I do not get the correct values. What am I missing here?

标签: c++ class
2条回答
倾城 Initia
2楼-- · 2019-06-23 16:49

I would suggest writing a non-member function that calculated the int based on the input string, and then use that in Circle's constructor initialization list.

std::string foo(int area) { .... }

then

Circle :: Circle(int area, string str) : box(foo(str)) { .... }

You can only initialize a non-static data member in the initialization list. Once you get into the constructor body, everything has been initialized for you and all you can do is perform modifications to the data members. So one variant of your code which would compile if Box had a default constructor would be

Circle :: Circle(int area, string str) : area(area)
{
  // calculate int_str
  ....
  box = Box(int_str);
}
查看更多
孤傲高冷的网名
3楼-- · 2019-06-23 16:58

In constructor of Circle you are trying to create an instance of Box, which is too late because by the time the body of constructor will be executed, the members of Circle shall be constructed already. Class Box either needs a default constructor or you need to initialize box in an initialization list:

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)) { }
    ...
}
查看更多
登录 后发表回答