次の 2 つのユースケースの動作が異なるのはなぜですか?
組み込み型の例:
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
何か不足していますか?ここで達成しようとしているのは、ユーザーが直接色を変更できないようにすることです。変更したい場合は、ラッパー クラスを介して行う必要があります。