c ++:实例化对象 [英] c++: instantiate object
问题描述
可能重复:
C ++对象实例化与赋值
C ++并且想知道在实例化一个对象之间有什么区别(如果有)
int main(){
载体, int> x(2);
}
或
int main(){
vector< int> x = int> (2)。
}
,除了后者需要更长时间写入。提前感谢!
差异主要是语法:
-
矢量< int>
-
向量< int> ; x = vector< int>(2);
是复制初始化。
后者正式要求类具有可访问的复制构造函数,但实际上,复制将被省略,并且两个版本产生完全相同的代码。
-
< >vector< int> x = vector< int>(vector< int>(vector< int>(2)));
Possible Duplicate:
C++ Object Instantiation vs Assignment
I am quite new to C++ and was wondering what is the difference(if any) between instantiating an object as
int main () {
vector< int > x(2);
}
or
int main () {
vector< int > x = vector< int > (2);
}
except for the fact that the latter takes longer to write. Thanks in advance!
The difference is largely grammatical:
vector<int> x(2);
is direct initialization.vector<int> x = vector<int>(2);
is copy initialization.
The latter formally requires that the class have an accessible copy constructor, but in practice the copy will be elided and the two versions produce exactly the same code.
You should always prefer direct initialization.
You can also go insane:
vector<int> x = vector<int>(vector<int>(vector<int>(2)));
这篇关于c ++:实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!