繁体   English   中英

复制构造函数可以成为转换运算符吗?

[英]can copy constructor be a conversion operator?

考虑下面的代码。

#include <iostream>

using namespace std;


class Test
{
        private:
                int x,y;
        public:
                Test () {
                        cout <<" Inside Constructor "<<endl;
                        x=100;
                }   
                explicit Test (const Test & t)
                {   
                        cout <<"Inside Copy Constructor "<<endl;
                        x = t.x;
                }   
                void display()
                {   
                        cout <<" X is "<<x<<endl;
                }   

};



int main (int argc, char ** argv){
  Test t;
  t.display(); 

 cout <<"--- Using Copy constructor "<<endl;
 Test t2(t);
 t2.display (); 

 Test t3=t2;
 t3.display (); 

}

测试(const Test&t)->是副本构造函数

题:

用作“转换运算符”吗? 测试t3 = t2 [在这里,复制构造函数被视为转换运算符]

我不确定我的理解是否正确? 如果我错了,请纠正我?

 Test t3=t2;

如果copy c-torexplicit ,则永远不要编译。

n3337 12.3.1 / 3

非显式复制/移动构造函数(12.8)是转换构造函数。 隐式声明的copy / move构造函数不是显式的构造函数。 可能需要进行隐式类型转换。

这句话似乎出现在以下问题上: 隐式副本构造函数

因此,就您而言,它不是转换构造函数。

在C ++中,术语转换暗含两种不同的类型: 源类型目标类型

根据定义,复制构造函数仅涉及一种类型:源类型和目标类型相同。 因此,不能将其称为转换函数。

当您使用T t3 = t2时。 它将调用您尚未定义的赋值运算符。

暂无
暂无

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

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