visual studio-用于隐式类型转换的C++构造函数
visual studio - C++ Constructor for Implicit Type Conversion
我有这些代码:
class Type2 {
public:
Type2(const Type1 & type);
Type2(int);
const Type2 & operator=(const Type2 & type2);
//....
};
...
Type1 t1(13);
Type2 t2(4);
t2=t1;
正如我所理解的,Type2的1参数构造函数,每个构造函数都没有显式关键字,这意味着任何Type1对象或int值都可以隐式转换为Type2对象。
但在最后一行t2=t1,MS Visual Studio给我这个编译错误:
错误C2679:二进制"=":没有运算符已找到,它接受右侧操作数类型为"Type1"(或者没有可接受的转换)。。。。
似乎MS Visual Studio坚持t2=t1必须匹配lhs=Type2和rhs=Type1的赋值运算符。为什么它不能隐式地将rhs强制转换为t2,然后使用Type2=Type2运算符进行复制?
我找到了答案。因为我的Type1有一个转换操作员
class Type1 {
public:
Type1 (int );
operator Type2() ;//casting to Type2
....
};
这就是所谓的"双向隐式转换"
此代码:
#include <iostream>
using ::std::cerr;
class Barney;
class Fred {
public:
Fred() { }
Fred(const Barney &b) { cerr << "Using conversion constructor.n"; }
};
class Barney {
public:
Barney() { }
operator Fred() const { cerr << "Using conversion operator.n"; return Fred(); }
};
int main(int argc, const char *argv[])
{
const Barney b;
Fred f;
f = b;
return 0;
}
在gcc 4.6:中生成此错误
g++ -O3 -Wall fred.cpp -o a.out
fred.cpp: In function ‘int main(int, const char**)’:
fred.cpp:23:8: error: conversion from ‘const Barney’ to ‘const Fred’ is ambiguous
fred.cpp:21:17: note: candidates are:
fred.cpp:16:4: note: Barney::operator Fred() const
fred.cpp:10:4: note: Fred::Fred(const Barney&)
fred.cpp:7:7: error: initializing argument 1 of ‘Fred& Fred::operator=(const Fred&)’
Compilation exited abnormally with code 1 at Sun Jun 19 04:13:53
现在,如果我在operator Fred()
之后删除const
,它就会编译并使用转换构造函数。如果我还从main
中b
的声明中删除了const
,那么它更喜欢转换运算符。
这一切都符合过载解决规则。当gcc不能在转换运算符和转换构造器之间进行选择时,它会产生适当的模糊度误差。
我注意到,在您给出的示例中,转换运算符缺少一个const
。这意味着永远不会出现使用转换运算符或转换构造函数不明确的情况。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为