有没有办法在C ++中初始化一个成员变量(一个类)? [英] Is there a way to late-initialize a member variable (a class) in C++?

查看:288
本文介绍了有没有办法在C ++中初始化一个成员变量(一个类)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am coming from the Java background. I have the following program.

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

,我想让变量第一保持未初始化,直到我在 Second()的构造函数中专门初始化它。有办法吗?或者我只剩下2个选项?:

In class Second, I wanted to variable first to remain uninitialized until I specifically initialize it in Second()'s constructor. Is there a way to do it? Or am I just left with 2 options?:


  1. 提供无参数的构造函数。

  2. 使用一些默认值初始化它,然后重新分配所需的值。

不能在具有正确值的初始化器列表中初始化第一,因为该值是在某些操作之后获得的。因此,第一的实际所需值仅在 Second()构造函数中可用。

I can't initialize first in the initializer-list with the right value, since the value is obtained after some operation. So, the actual required value for first is available in Second() constructor only.

推荐答案

我的建议:使用函数:

private: static int calculate_first(int input) {return input*5;}
explicit Second(int input) : first(calculate_first(input)) {}

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



或者:

Base classes will be initialized in the order they're declared in the class inheritance list, and then members will be initialized in the order that they're listed in the class, so the calculation can depend on non-static member-variables and base classes if they have already been initialized.


Alternatively:

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

Default constructor, then reassign:

explicit Second(int input) { first = input*5; }

假值,然后重新分配:

explicit Second(int input) : first(0) { first = input*5; }

使用boost :: optional:

Use boost::optional:

boost::optional<First> first;
explicit Second(int input) { first = input*5; }

使用堆:

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

新放置位置:

This is tricky and not suggested 
and worse in every way than boost::optional
So sample deliberately missing.
But it is an option.

这篇关于有没有办法在C ++中初始化一个成员变量(一个类)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆