初学者的问题 [英] Beginner's question

查看:60
本文介绍了初学者的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种写作方式有什么区别:


myClass a;

a = b;




myClass a = b;

我错误地认为它们是相同的(MSVC6)。


提前谢谢。


Pierre Couderc

解决方案

> myClass a;

a = b;


第一个staement将通过调用myClass的

默认构造函数来执行默认的iniitalization。第二个语句将调用myClass的

赋值运算符。

myClass a = b;


这将执行复制初始化。复制初始化意味着在必要时首次调用

用户定义的转换后,使用复制构造函数初始化

对象。

谢谢你推荐。

Pierre Couderc




Srini




Pierre Couderc写道:

这两种写作方式有什么区别:

myClass a;
a = b;


a是默认构造的,然后赋值运算符用于

将b分配给a。


myClass a = b;


这是初始化,而不是分配。这与以下内容完全相同:


myClass a(b); //如果b与

相同或者:


myClass a(myClass(b)); //如果b是不同类型的


在任何一种情况下,都会调用复制构造函数和可能的另一个构造函数

,并且不使用赋值运算符。 />
我错误地认为它们是相同的(MSVC6)。

提前谢谢。

Pierre Couderc



What is the difference between these 2 ways of writing :

myClass a;
a=b;

and
myClass a=b;
I wrongly thought they were identical (MSVC6).

Thank you in advance.

Pierre Couderc

解决方案

> myClass a;

a=b;

The first staement would perform default iniitalization by calling the
default constructor of myClass. The second statement would call the
assignment operator of myClass.
myClass a=b;
This would perform copy initialization. Copy initialization means the
object is initialized using the copy constructor, after first calling a
user-defined conversion if necessary.
Thank you in advance.

Pierre Couderc



Srini



Pierre Couderc wrote:

What is the difference between these 2 ways of writing :

myClass a;
a=b;

a is default constructed first, then the assignment operator is used to
assign b to a.
and
myClass a=b;
This is initialization, not assignment. This is identical to:

myClass a(b); // if b is the same type as a

or:

myClass a(myClass(b)); // if b is of different type

In either case, the copy constructor and possibly another constructor
are called and no assignment operator is used.
I wrongly thought they were identical (MSVC6).

Thank you in advance.

Pierre Couderc




这篇关于初学者的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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