具有构造函数类型转换和转换操作符的转换序列
sequence of conversions with contsructor-type conversions and conversion operators
我读到过标准转换可以在转换操作符或构造函数类型转换实现的转换之前或之后。另一方面,不允许使用包含两个转换操作符的序列
不允许有两个构造函数类型转换的序列
我开始测试这个,得到了不同的结果。我使用的是MSVC2010
在第一组代码中,这失败了:这很好,因为它意味着两个转换操作符的序列:一个从myString到myType,另一个从myType到int
在第二串代码这不会失败:虽然我认为它意味着两个构造函数转换的序列:一个从int到myType,另一个从myType到myString。
谁能给我解释一下我错过了什么?许多谢谢,第一群
class myType {
public:
myType(): val(10) {}
myType(const myType &orig): val(orig.val) {}
myType(int v1): val(v1) {}
bool hasSameValue(const myType &o2) {
return (o2.val == val); }
int getVal() {
return val; }
operator int() { return val; }
private:
int val;
};
#include <string>
class myString {
public:
myString(): val("I Dont Know you") {}
myString(const myString &orig): val(orig.val) {}
myString(myType v1): val("Really Dont know you") {}
bool hasSameValue(const myString &o2) {
return (o2.val == val); }
std::string getVal() {
return val; }
std::string getString() {return val;}
operator myType() { return 1000; }
private:
std::string val;
};
#include <iostream>
using namespace std;
int main() {
int b = 36;
myString sMe;
myString sYou(b);
cout << "sYou: " << sYou.getString() << endl;
cout << "sMe: " << sMe.getString() << endl;
myType a = sMe;
cout << a.getVal() << endl;
int b1 = sMe;
return 1;
}
第二群
class myType {
public:
myType(): val(10) {}
myType(const myType &orig): val(orig.val) {}
myType(int v1): val(v1) {}
bool hasSameValue(const myType &o2) {
return (o2.val == val); }
int getVal() {
return val; }
private:
int val;
};
#include <string>
class myString {
public:
myString(): val("I Dont Know you") {}
myString(const myString &orig): val(orig.val) {}
myString(myType v1): val("Really, I Dont Know you") {}
bool hasSameValue(const myString &o2) {
return (o2.val == val); }
std::string getVal() {
return val; }
std::string getString() {return val;}
private:
std::string val;
};
#include <iostream>
using namespace std;
int main() {
myType me;
int a = 34;
int b = 36;
myType you(a);
bool sameVal = you.hasSameValue(b);
cout << sameVal << endl;
cout << "you: " << you.getVal() << endl;
cout << "me: " << me.getVal() << endl;
myString sMe;
myString sYou(b);
cout << "sYou: " << sYou.getString() << endl;
cout << "sMe: " << sMe.getString() << endl;
return 1;
}
myString sYou(b);
只涉及一个隐式转换。第二个转换是显式;你在调用构造函数。所以它编译。
相反,下面的不编译:
void func(myString blah) { ... }
func(b);
相关文章:
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- Clang vs GCC vs MSVC模板转换操作符-哪个编译器是正确的
- 模板类型转换操作符=
- 链接隐式转换操作符
- 强制转换操作符函数在g++中可以很好地编译,但在其他编译器中不行.为什么
- 当目标类有多个构造函数时,消除强制转换操作符的歧义
- 删除转换操作符
- 强制转换操作符重载和引用
- 实现没有临时的转换操作符
- 不同的强制转换操作符被不同的编译器调用
- 为什么模板化的用户定义转换操作符能够确定其返回类型?
- const转换操作符
- 调用转换操作符不能用于静态const变量
- 内部编译器错误-开关表达式中的模板化转换操作符
- 强制转换操作符可以是显式的吗?
- 不同的编译器使用不同的强制转换操作符
- 是否需要重载类的强制转换操作符?
- 类型转换操作符重载——Visual studio 2013内部错误
- ' auto x = type{…} '初始化语法和'显式'转换操作符- clang vs gcc
- 是否有方法为任何指针类型定义转换操作符