C ++如何初始化成员对象? [英] C++ How to Initialize member object?

查看:168
本文介绍了C ++如何初始化成员对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子的第一部分有一些方法来初始化(?)类型C的成员变量c?或者必须使用示例第二部分中所示的new()方法?

Is there some way to initialize(?) member variable c of type C in the first part of the below example? Or must I use the new() method shown in the second part of the example?

B类将A类视为注入依赖。 B类也是由C类组成的。

Class B takes class A as an injected dependency. So does class C. Class B is additionally composed of class C.

如何获取注入的A到B的成员C?

How do I get the injected A to B's member C?

第1部分

class A { // ...; };

class C {
public:
    C(A &a) : a(a) {}   // constructor
};


// Does not work as is.  Want to make compiler manage C lifetime.
class B {
public:
    B(A &a);    // constructor

    C c(a);     // member variable
};

// constructor
B::B(A &a) : a(a) {
}

第2部分

// Works, but requires programmer to manage C's lifetime.
class B {
public:
    B(A &a);    // constructor

    C *c;       // member variable
};

// constructor
B::B(A &a) : a(a) {
    c = new C(a);
}

下面几个好的答案!我的道歉为混乱的例子。我已经投票了所有好的答案和问题。不幸的是,我只能将一个答案标记为接受的答案,所以我选择第一个给我的啊哈时刻,我看到解决我的真正的问题,这比我的跛脚示例更复杂。

Several good answers below! My apologies for the confusing example. I have up-voted all of the good answers and questions. Unfortunately I can only mark one answer as the accepted answer, so I am choosing the first one which gave me the "ah-ha" moment in which I saw the solution to my real problem, which was more complex than my lame example here.

推荐答案

成员变量在构造函数的初始化列表中初始化(在body之前),因此您需要这样做:

Member variables are initialized in constructor's initialization list (before body) so you need to do that:

B::B(A &a)
    : c(a) // Calls constructor C(a) on member c
{}

这篇关于C ++如何初始化成员对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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