4

我有一个类MyClass,我需要在默认构造函数中std::array创建一个。std::vector但是,这个类有一个数据成员,它是一个引用(类型Something),它也需要在构造函数中初始化,我不能在默认构造函数中这样做。

我应该如何解决这个问题?

class MyClass{
public:
    MyClass(); //Cannot instantiate s??
    MyClass(Something& s);
    Something& s;
}

MyClass array[10];   // MyClass needs a default constructor but a default 
                     // constructor won't be able to initialize s
4

3 回答 3

6

A class with a reference member needs to set the reference in its constructors. In most cases this means, that the class cannot have a default constructor. The best way to solve the problem is use a pointer instead of a reference:

class MyClass{
public:
    MyClass() : s_(0) {}
    MyClass(Something* s) : s_(s) {}
    Something* s_;
}
于 2014-04-05T00:48:22.663 回答
1

As I commented above, by the description alone, I would say that it's a classical case where s should be a Something* rather than a Something&...

OTOH, this work perfectly, so you don't need a default constructor if you just initialize each element of your array:

struct Something { };

struct MyClass {
  MyClass(Something& ss) : s{ss} {}
  Something& s;
};

int main() {
  Something a, b, c, d;
  Something v[10] = { a, b, c, d, a, b, c, d, a, b };
  return 0;
}
于 2014-04-05T00:49:49.507 回答
1

你也可以这样做:

class MyClass{
public:
    MyClass() : s_(0) {}
    MyClass(Something& s) : s_(&s) {}
    Something* s_;
}
于 2017-02-21T10:44:56.193 回答