Default constructor for a class with a reference data member?

不羁岁月 提交于 2019-12-05 18:59:10

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_;
}

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

Your can also do this:

class MyClass{
public:
    MyClass() : s_(0) {}
    MyClass(Something& s) : s_(&s) {}
    Something* s_;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!