具有构造函数类型转换和转换操作符的转换序列

sequence of conversions with contsructor-type conversions and conversion operators

本文关键字:转换 操作符 构造函数 类型转换      更新时间:2023-10-16

我读到过标准转换可以在转换操作符或构造函数类型转换实现的转换之前或之后。另一方面,不允许使用包含两个转换操作符的序列
不允许有两个构造函数类型转换的序列

我开始测试这个,得到了不同的结果。我使用的是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);