C ++ - 嵌套非指针类的构造函数

时间:2016-02-15 16:30:12

标签: c++

外部类中有非指针(body)嵌套类。我需要在进行一些计算后从外部类构造函数中调用它的构造函数。怎么办?

class nested
{
  int value;
  nested(int x) {value=x;};
  nested() {value=0;};
};
class outer:
{
  nested n;
  nested *pn; 
  outer(int x);
};
outer::outer(int x1)
{
  x = x1;
  y = x + 1 *x*x;//some long calculations needed for nested
  pn = new nested(y); //this is trivial
  n = nested(y); //??? how to initialize non-pointer class?????
}

1 个答案:

答案 0 :(得分:1)

一种解决方案是计算y并将其存储为成员变量。这样,您可以在初始化依赖于它的任何内容之前计算并缓存它。

class outer
{
public:
    outer(int x)
        , y(CalculateY(x))
        , n(y)
        , pn(new nested(y))
    {}

private:
    int CalculateY(int x); // this can be static

    int y;    
    nested n;
    nested *pn;
};

注意

必须在依赖于它的任何事物之前声明

int y,因为成员变量按照它们被声明的顺序初始化。