【问题标题】:C++ - constructor for nested non-pointer classC++ - 嵌套非指针类的构造函数
【发布时间】:2016-02-15 16:30:11
【问题描述】:

外部类中存在非指针(体)嵌套类,计算后需要从外部类构造函数中调用它的构造函数,怎么办?

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?????
}

【问题讨论】:

  • 顺便说一句,你可以做 nested(int x = 0) { value = x; } 并删除无参数构造函数。
  • @TadeuszKopec 这里nested 有一个默认构造函数。
  • @zenith 仍然问题归结为“如何为成员的自定义构造函数提供参数”,并且它存在于 SO 上的无数实例中。如果您知道有关它的规范问题,请出示。

标签: c++


【解决方案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 必须在任何依赖它的东西之前声明,因为成员变量是按照声明它们的顺序初始化的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多