在C ++中使用显式副本构造函数 [英] use of explicit copy constructor in C++

查看:97
本文介绍了在C ++中使用显式副本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


有人可以让我知道带有relevent示例的显式副本构造函数的用途吗?请参阅以下代码以及注释.我正在使用g ++编译器.

1#include< iostream> ;;
2
3使用命名空间std;
4
5级Y {
6位公众:
7 Y()
8 {}
9 Y(int x)
10 {}
11个显式Y(const Y&){}
12
13};
14
15
16 int main()
17 {
18 Y obj; //作品
19 Y obj2 = obj; //不起作用.
20返回0;
21}
22

Hi,
Can someone let me know what is the use of explicit copy constructor with relevent examples? Please see the following code along with comments. I am using g++ compiler.

1 #include<iostream>;
2
3 using namespace std;
4
5 class Y {
6 public:
7 Y()
8 {}
9 Y( int x)
10 {}
11 explicit Y(const Y&){}
12
13 };
14
15
16 int main()
17 {
18 Y obj; // works
19 Y obj2 = obj; // doesn''t work.
20 return 0;
21 }
22

推荐答案

explicit 表示仅允许使用明确的声明来说明正在创建对象."当你写的时候:

A a;
A b = a;

第二行是隐式的复制构造,如果标记了复制构造函数explicit,则编译器不会让它发生.如果您写:

A a;
a b(a);

您明确地说这是一个副本结构",无论您标记了副本构造函数(只要它是公共的),编译器都会使它发生.

干杯,

Ash
explicit means "Only allow objects to be created with an explicit statement that construction is happening." When you write:

A a;
A b = a;

the second line is implicitly a copy construction and the compiler won''t let it happen if you''ve marked the copy constructor explicit. If you write:

A a;
A b( a );

You''re explicitly saying "this is a copy construction" and the compiler lets it happen, whatever you''ve marked the copy constructor (provided it''s public).

Cheers,

Ash


带有单个参数的构造函数之前的关键字"explicit"避免了自动类型转换.

如果您使用的类具有许多构造函数和赋值运算符覆盖,则可能是必需的.

更好的例子可能是:

The keyword "explicit" before constructor with single argument avoids automatic type conversion.

It may be necesary if you are using classes with many constructor and assignement operator override.

The better example would probably be:

class Y {
 public:
 Y()
 {}
 explicit Y( int x)
 {}
 Y(const Y&){}

};

int _tmain(int argc, _TCHAR* argv[])
{
 Y obj; // works
 Y obj2 = 0; // doesn''t work.
 Y obj3 = Y(0); // does work.

	return 0;
}


这篇关于在C ++中使用显式副本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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