0

我在模板和组合式编码方面遇到了一些麻烦。我在另一个带有 *this 参数的构造函数中创建了一个对象。对不起,如果我不清楚。代码如下:

在 external.h 文件中:

class outer {
  public:
    outer(int w, int l);
    int getWidth();
    int getLength();
  private:
    inner<outer> test(*this);
    int width;
    int length;
};

outer::outer(int w, int l) {
  width = w;
  length = l;
}

int outer::getLength() {
  return length;
}

在 inner.h 文件中

template<typename T>
class inner {
  public:
    inner(T &name);
  private:
    int top;
    int bot;
};

template<typename T>
inner<T>::inner(T &name) {
    top = name.getLength() /2;
    bot = -name.getLength() / 2;
}

我不知道这是否被允许,因为我在网上找不到任何解决这个问题的东西。编译器在 outer.h 中的 *this 语句存在问题。

在此先感谢您的帮助。

4

1 回答 1

3

如果您使用的是 C++03,则必须在构造函数中执行初始赋值。

class outer {
  public:
    outer(int w, int l);
    int getWidth();
    int getLength();
  private:
    // Member variables are initialized in the order they are declared here.
    int width;
    int length;
    inner<outer> test;
};

outer::outer(int w, int l)
  : width(w)
  , length(l)
  , test(*this)
{
}

编辑: Kerrek SB 还观察到需要更改变量的顺序。它们按照您在类中声明它们的顺序进行初始化,并且test 需要最后初始化,因此初始化其他变量。

于 2013-03-19T00:04:07.747 回答