C++ 如何在构造函数中初始化 const 字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1423696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:55:53  来源:igfitidea点击:

How to initialize a const field in constructor?

c++constructorconstctor-initializer

提问by puccio

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?

想象一下,我有一个 C++ 类 Foo 和一个类 Bar,它们必须使用传递 Foo 指针的构造函数创建,并且该指针旨在在 Bar 实例生命周期中保持不变。正确的做法是什么?

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.

欢迎任何建议。

回答by Jim Buck

You need to do it in an initializer list:

您需要在初始化列表中执行此操作:

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

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

(请注意,我重命名了传入变量以避免混淆。)

回答by SingleShot

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& foo;

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

回答by ezpz

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

初始化 const 成员和其他特殊情况(如父类)可以在初始化列表中完成

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

回答by KeithB

You need to initialize foo in the initializer list.

您需要在初始化列表中初始化 foo。

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

回答by AraK

Use a reference:

使用参考:

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

You can then refer to fooeasily in Bar:

然后您可以foo轻松地 参考Bar

foo.doSomething();

回答by John Ledbetter

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

尝试: Bar(Foo* xfoo) : foo(xfoo) {}