为什么以下两个用例的行为不同?
内置类型的示例:
class Test
{
operator const char*() {
return "operator const char*() called";
}
operator char*() {
return const_cast<char*> ("operator char*() called");
// a really ugly hack for demonstration purposes
}
};
Test test;
const char *c_ch = test; // -> operator const char*() called
char *ch = test; // -> operator char*() called
好的,一切正常。不,让我们用用户定义的类型来试试:
class ColorWrapper
{
operator const Color() {
cout << "operator const Color() called" << endl;
return Color(10, 20, 30);
}
operator Color() {
cout << "operator Color() called" << endl;
return Color(11, 22, 33);
}
};
ColorWrapper cw;
const Color c_col = cw;
Color col = cw;
情况看起来相同;但现在,GCC 开始抱怨:
error: conversion from 'ColorWrapper' to 'const Color' is ambiguous
error: conversion from 'ColorWrapper' to 'Color' is ambiguous
我错过了什么吗?我在这里想要实现的是防止用户直接更改颜色。如果他们想改变它,他们必须通过包装类来完成。