避免调用成员变量的构造函数 [英] Avoid calling constructor of member variable
问题描述
我很确定这个问题已经被问过了。但即使搜索了几分钟,我没有找到任何可以回答我的问题的职位。我有以下C ++ - 类:
I'm pretty sure that this question has already been asked. But even after searching for some minutes, I didn't find any post which could answer my question. I have the following C++-class:
// Header-File
class A
{
public:
A();
private:
B m_B;
C m_C;
};
// cpp-File
A::A()
: m_B(1)
{
m_B.doSomething();
m_B.doMore();
m_C = C(m_B.getSomeValue());
}
现在我想避免 c $ c> A 调用 C m_C
的任何构造函数。因为在 A :: A()
的最后一行,我无论如何都要初始化 m_C
需要首先准备 m_B
。我可以为 class B
提供一个空的默认构造函数。但是这不是想法。
I now would like to avoid the class A
to call any constructor of C m_C
. Because on the last line in A::A()
, I'm anyways going to initialize m_C
myself because I need to prepare m_B
first. I could provide an empty default constructor for class B
. But that's not the idea.
我已经尝试将 m_C(NULL)
添加到init- A :: A()
。有时它工作,有时它说没有构造函数以 NULL
作为参数。
I have already tried to add m_C(NULL)
to the init-list of A::A()
. Sometimes it worked, sometimes it said there was no constructor taking NULL
as an argument.
m_C
左未初始化?我知道使用指针, m_C(NULL)
-way工程。我不想使用 new
动态分配它。
So how can I have m_C
left uninitialized? I know that with pointers, the m_C(NULL)
-way works. And I don't want to allocate it dynamically using new
.
任何想法都是值得赞赏的。
Any idea is appreciated.
推荐答案
您要求的是禁止的 - 正确的。这确保每个成员都被正确初始化。
What you ask is forbidden - and correctly so. This ensures that every member is correctly initialized. Do not try to work around it - try to structure your classes that they work with it.
想法:
- C有一个无效的构造函数
- C具有使该类可用的初始化方法
- 它已经被正确初始化或没有初始化,如果没有初始化就返回适当的错误。
这篇关于避免调用成员变量的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!