How to initialize a const field in constructor?

天涯浪子 提交于 2019-11-26 12:15:31

问题


Imagine I have a C++ class Foo and a class Bar which has to be created with a constructor in which a Foo pointer is passed, and this pointer is meant to remain immutable in the Bar instance lifecycle. What is the correct way of doing it?

In fact, I thought I could write like the code below but it does not compile..

class Foo;

class Bar {
public:
    Foo * const foo;
    Bar(Foo* foo) {
        this->foo = foo;
    }
};

class Foo {
public:
  int a;
};

Any suggestion is welcome.


回答1:


You need to do it in an initializer list:

Bar(Foo* _foo) : foo(_foo) {
}

(Note that I renamed the incoming variable to avoid confusion.)




回答2:


I believe you must do it in an initializer. For example:

Bar(Foo* foo) : foo(foo) {
}

As a side note, if you will never change what foo points at, pass it in as a reference:

Foo& foo;

Bar(Foo& foo) : foo(foo) {
}



回答3:


Initializing const members and other special cases (such a parent classes) can be accomplished in the initializer list

class Foo {
private:
   const int data;
public:
   Foo(int x) : data(x) {}
};

Or, similarly, for parent initialization

class Foo {
private:
   int data;
public:
   Foo(int x) : data(x) {}
};

class Bar : Foo {
public:
   Bar(int x) : Foo(x) {}
};



回答4:


You need to initialize foo in the initializer list.

class Bar {
    Foo* const foo;
  public:
    Bar(Foo* f) : foo(f) {...}
};



回答5:


Use a reference:

Foo& foo;
Bar(Foo& f) : foo(f) { }

You can then refer to foo easily in Bar:

foo.doSomething();



回答6:


try: Bar(Foo* xfoo) : foo(xfoo) {}



来源:https://stackoverflow.com/questions/1423696/how-to-initialize-a-const-field-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!