可以将构造函数复制为转换运算符

can copy constructor be a conversion operator?

本文关键字:转换 运算符 复制 构造函数      更新时间:2023-10-16

请考虑以下代码。

#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 (); 
}
Test

(const Test & t) -> 是一个复制构造函数

问题:

是否与"转换运算符"相同?测试 t3 = t2 [此处复制构造函数被视为转换运算符]

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

 Test t3=t2;

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

N3337 12.3.1/3

非显式复制/移动构造函数 (12.8) 是转换构造函数。隐式声明的副本/移动构造函数不是显式构造函数;对于隐式类型转换,可以调用它。

这句话似乎是以下问题:隐式复制构造函数

因此,在您的情况下,它不是转换构造函数。

在C++中,术语转换意味着两种不同的类型:源类型和目标类型

根据定义,复制构造函数只涉及一种类型:源类型和目标类型是相同的。所以它不能称为转换函数。

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