有没有办法在C++中初始化成员变量(类)?

lin*_*asy 8 c++ constructor initialization class lazy-initialization

我来自Java背景.我有以下程序.

#include <string>
#include <iostream>

class First {
    public:
    First(int someVal): a(someVal) {

    }
    int a;
};

class Second {
    public:
    First first;
    Second()  {   // The other option would be to add default value as ": first(0)"
        first = First(123);

    }
};

int main()
{
    Second second;
    std::cout << "hello" << second.first.a << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在课堂上Second,我希望变量first保持未初始化,直到我专门初始化它Second()'s constructor.有办法吗?或者我只剩下2个选项?:

  1. 提供无参数构造函数.
  2. 使用某个默认值对其进行初始化,然后重新分配所需的值.

我无法first在初始化列表中使用正确的值初始化,因为该值是在某些操作之后获得的.因此,实际所需的值仅firstSecond()构造函数中可用.

Moo*_*uck 7

我的建议:使用功能:

private: static int calculate_first(int input) {return input*5;}
explicit Second(int input) : first(calculate_first(input)) {}
Run Code Online (Sandbox Code Playgroud)

基类将按照它们在类继承列表中声明的顺序进行初始化,然后成员将按照它们在类中列出的顺序进行初始化,因此计算可以依赖于非静态成员变量和基数类,如果他们已经被初始化.


或者:

默认构造函数,然后重新分配:

explicit Second(int input) { first = input*5; }
Run Code Online (Sandbox Code Playgroud)

虚拟价值,然后重新分配:

explicit Second(int input) : first(0) { first = input*5; }
Run Code Online (Sandbox Code Playgroud)

使用boost :: optional:

boost::optional<First> first;
explicit Second(int input) { first = input*5; }
Run Code Online (Sandbox Code Playgroud)

使用堆:

std::unique_ptr<First> first;
explicit Second(int input) { first.reset(new First(input*5));}
Second(const Second& r) first(new First(*(r->first))) {}
Second& operator=(const Second& r) {first.reset(new First(*(r->first)));}
Run Code Online (Sandbox Code Playgroud)

新位置:

This is tricky and not suggested 
and worse in every way than boost::optional
So sample deliberately missing.
But it is an option.
Run Code Online (Sandbox Code Playgroud)

  • @linuxeasy:基类将按照它们在类继承列表中声明的顺序进行初始化,然后成员将按照它们在类中列出的顺序进行初始化,因此计算_can_依赖于非静态成员 - 变量和基类_if_它们已经初始化. (2认同)