我正在阅读有关转换操作符的文章,并了解了它们所做的工作的要点。简而言之,当您想要从用户定义的类型转换到内置类型时,它们是非常必要的。这可能还有更多的用途。一个很好的例子是:
class Tiny {
int i;
public:
Tiny (int i) : i(i) {}
operator int() const { return i; }
};
int main() {
Tiny c1 = 2;
int i = c1;
std::cout << i << std::endl;
}这会输出2.太好了。我能理解。为了加强我的理解,请考虑下面的例子:
class Tiny {
public:
class Bad_range {};
Tiny (int i) {
std::cout << "ctor called" << std::endl;
}
operator int() const {
std::cout << "conversion ctor called" << std::endl;
}
};
int main() {
Tiny c1 = 2;
Tiny c2 = 62;
Tiny c3 = c2 - c1;
}这一产出如下:
ctor called
ctor called
conversion ctor called
conversion ctor called
ctor called我明白为什么“ctor打电话”来了两次。我指的是微小的c1 =2,间接的意思是微小的c1 =微小的(2)。所以这很好。我不明白的是为什么“转换ctor”被叫了两次。
同样,还有一个包含操作符重载的快照:
class Tiny {
int i;
public:
class Bad_range {};
Tiny (int i) : i(i) {
std::cout << "ctor called" << std::endl;
}
operator int() const {
std::cout << "conversion ctor called" << std::endl;
}
Tiny operator-(Tiny a) {
return this->i - a.i;
}
};
int main() {
Tiny c1 = 2;
Tiny c2 = 62;
Tiny c3 = c2 - c1;
} 这一产出如下:
ctor called
ctor called
ctor called那么,这是否意味着运算符重载比转换操作符具有更高的优先级?
发布于 2020-04-21 19:43:39
这是因为在第一个示例中没有为operator-定义Tiny。通过以下方式:
Tiny c3 = c2 - c1; 为了让c1 - c2编译,编译器必须将两个操作数转换为int,然后使用int的operator-。这是标准转换序列的一部分,重载解析用于查看operator-的过载是否能工作。由于没有提供重载,编译器看到它可以将两个值转换为int,因此它调用该重载。
https://stackoverflow.com/questions/61351807
复制相似问题