[英]How to initialize class members without using the copy constructor
I'm now writing C++ code to do some maths. 我现在正在编写C ++代码来做一些数学运算。 However, it seems impossible to use normal constructors to initialize class members. 但是,似乎不可能使用常规构造函数来初始化类成员。
To get instantiated, the constructor of A is first called. 要实例化,首先调用A的构造函数。 By the time, p and q are just something like declaration so p and q don't get instantiated either. 到那时,p和q就像声明一样,所以p和q也不会被实例化。 So I should be able to call constructor of B to instantiate them. 所以我应该能够调用B的构造函数来实例化它们。 Is that right? 是对的吗? I think maybe my understanding of C++ classes is wrong somewhere so I post here to confirm. 我想也许我对C ++类的理解在某处是错误的,所以我在这里发帖确认。
class B{
// default constructor and copy constructor
}
class A{
private:
B p;
B q;
public:
explicit A(int _p, int _q);
}
// implementation
A::A(int _p, int _q){
// some computing goes here so I can't apply
// A::A(int _p, int _q):p{_p}, q{_q}
// p = B{_p}
// q = B{_q}
// this works
p{_p}; // Can't compile.
q{_q}; // What's wrong with this?
}
No, the constructor's behavior actually looks like this: 不,构造函数的行为实际上如下所示:
A::A(/* parameters */)
: /* member constructors called here, explicitly or by default, in order of declaration */
{
/* your constructor code */
}
In other words, by the time you enter a constructor's body, all class members are already fully constructed, either from the initializer list if it's specified there, or default-constructed if it is not in the initializer list. 换句话说,当您输入构造函数的主体时,所有类成员都已完全构造,如果在那里指定了初始化程序列表,则是初始化程序列表,如果它不在初始化程序列表中,则为默认构造。 Thus, your A
constructor behaves as if you wrote A::A(int _p, int _q) : p{}, q{} { /* code */ }
. 因此,您的A
构造函数的行为就像您编写了A::A(int _p, int _q) : p{}, q{} { /* code */ }
。 q = B{_q};
does not call the copy constructor; 不会调用复制构造函数; it constructs a temporary B
object and calls the copy or move assignment operator of q
, but since the compiler generates those for you in many cases, it compiles. 它构造一个临时B
对象并调用q
的复制或移动赋值运算符,但由于编译器在很多情况下为你生成它们,因此它会编译。 q{_q};
, as a statement, is simply not valid C++. ,作为一个声明,根本不是有效的C ++。
The problem is that you simply can't use initialization lists to perform assignments by the way you are trying . 问题是您根本无法使用初始化列表按照您尝试的方式执行分配。 And, since you can't initialize the variable at first, you are actually looking for an assignment (notice that p
and q
have already been default initialized ). 并且,由于您最初无法初始化变量,因此您实际上正在寻找一个赋值(注意p
和q
已经默认初始化 )。 When you write: 当你写:
p{_p};
q{_q};
It's just not valid syntax, since there is no operation defined over lvalue<initialization_list>
after the variable has already been initialized (at anywhere else out of the constructor's initialization list/variable declaration). 它只是无效的语法,因为在变量已经初始化之后(在构造函数的初始化列表/变量声明之外的任何其他地方),没有在lvalue<initialization_list>
定义的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.