可以将构造函数复制为转换运算符
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 ();
}
Test (const Test & t) -> 是一个复制构造函数
问题:
是否与"转换运算符"相同?测试 t3 = t2 [此处复制构造函数被视为转换运算符]
我不确定我的理解是否正确?如果我错了,请纠正我?
Test t3=t2;
如果copy c-tor
explicit
,则永远不要编译。
N3337 12.3.1/3
非显式复制/移动构造函数 (12.8) 是转换构造函数。隐式声明的副本/移动构造函数不是显式构造函数;对于隐式类型转换,可以调用它。
这句话似乎是以下问题:隐式复制构造函数
因此,在您的情况下,它不是转换构造函数。
在C++中,术语转换意味着两种不同的类型:源类型和目标类型。
根据定义,复制构造函数只涉及一种类型:源类型和目标类型是相同的。所以它不能称为转换函数。
当您使用 T t3 = t2 时。它将调用您尚未定义的赋值运算符。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 继承模板化转换运算符
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在模板化转换运算符中消除此构造的歧义?
- 为什么选择转换运算符的重载?
- 如何避免强制转换运算符 () 和访问运算符 [] 冲突?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 了解转换运算符的选择C++
- 多个隐式转换运算符
- 这个typedef和转换运算符语法是什么意思
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 类模板忽略了用户定义的转换运算符(非模板不忽略)
- 为什么在std::for_each()返回时调用转换运算符
- 为什么 std::optional 的强制转换运算符被忽略了
- 使用用户定义的转换运算符推导函数模板参数
- 模板转换运算符的分辨率不明确
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?