简体   繁体   English

C ++运算符重载奇怪的类型转换

[英]C++ operator overloading weird type conversion

I have simple c++ class vector and it has parameter constructor as follow: 我有简单的c ++类向量,它有参数构造函数如下:

Vector::Vector(int size){
   ...
}

Based on this implementation following lines are valid: 基于此实现,以下行有效:

Vector v(1);
Vector v2(94);

My question is I was testing my code and I came across this was also valid: 我的问题是我正在测试我的代码,但我发现这也是有效的:

Vector v = 1;

which called parameter constructor somehow. 以某种方式调用参数构造函数。 I also overloaded operator = but in this case it was never called. 我也重载了operator =但是在这种情况下它从未被调用过。 Is this normal behavior in c++? 这是c ++中的正常行为吗? How does a compiler treat above assignment as Vector v(1) ? 编译器如何将上面的赋值视为Vector v(1) I'm doing this in Xcode 5.0 (LLVM compiler) 我在Xcode 5.0(LLVM编译器)中这样做

It's not overloaded operator = , it's copy-initialization. 它没有重载operator = ,它是复制初始化。 If you want prevent such construction of vector, then you can use explicit constructor. 如果你想阻止这样构造vector,那么你可以使用explicit构造函数。

explicit Vector(int);

now 现在

Vector v = 1;

is incorrect. 是不正确的。

This happens due to 'Automatic Type Conversion' that compiler supports quietly. 这是由于编译器支持的“自动类型转换”而导致的。 That's why it works with no copy constructor. 这就是为什么它不使用复制构造函数。

Bruce Eckel tells in his book "Thinking in C++": Bruce Eckel在他的书“Thinking in C ++”中讲述:

The default constructor, copy-constructor, operator= and destructor can be synthesized automatically by compiler. 默认构造函数,copy-constructor,operator =和析构函数可以由编译器自动合成。

The following , x2 would call copy constructor in x2 = x1 ; 以下,x2将在x2 = x1中调用复制构造函数;

ClassX  x1() ;
ClassX  x2 =  x1 ;

The following , x4 would call copy assignment in x4 = x3 ; 以下,x4将在x4 = x3中调用复制赋值;

ClassX  x3() ;
ClassX  x4() ;
x4 = x3 ;

If ClassX has explicit in copy construtor , then 如果ClassX有明确的复制construtor,那么

ClassX x5(x1) ;  //this will compiled ok 
ClassX x5 = x1 ; //This will fail while compiled

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM