我正在编写一个 String 类。我希望能够分配我的字符串,例如;
a = "foo";
printf(a);
a = "123";
printf(a);
int n = a; // notice str -> int conversion
a = 456; // notice int -> str conversion
printf(a);
我已经为我的 operator=() 方法分配了字符串到整数的转换。我如何声明另一个 operator=() 以便我可以执行反向方法?
当我声明另一个时,它似乎覆盖了前一个。
String::operator const char *() {
return cpStringBuffer;
}
String::operator const int() {
return atoi(cpStringBuffer);
}
void String::operator=(const char* s) {
ResizeBuffer(strlen(s));
strcpy(cpStringBuffer, s);
}
bool String::operator==(const char* s) {
return (strcmp(cpStringBuffer, s) != 0);
}
//void String::operator=(int n) {
// char _cBuffer[33];
// char* s = itoa(n, _cBuffer, 10);
// ResizeBuffer(strlen(_cBuffer));
// strcpy(cpStringBuffer, _cBuffer);
//}
最佳答案
单参数构造函数可以充当 int->String 转换,而所谓的转换运算符则执行相反的 int->String
class String
{
public:
String(int) {} // initialization of String with int
String& operator=(int) {} // assignment of int to String
operator int() const {} // String to int
};
但是请注意,这些转换将隐式发生,您很容易被咬到。假设您将扩展此类以也接受 std::string
参数和转换
class String
{
public:
String(int) {} // int to String
String(std::string) {} // std::string to String
// plus two assignment operators
operator int() const {} // String to int
operator std::string const {} // String to std::string
};
你会有这两个函数重载
void fun(int) { // bla }
void fun(std::string) { // bla }
现在尝试调用 fun(String())
.你会得到一个编译错误,因为有多个 - 同样可行的 - 隐式转换。这就是 C++98 允许关键字 explicit
的原因在单参数构造函数之前,C++11 将其扩展为 explicit
转换运算符。
所以你会写:
class String
{
public:
explicit String(int) {} // int to String
explicit operator int() const {} // String to int
};
隐式转换可能是合法的一个例子是对于想要转换为 bool
的智能指针类。或者(如果它们是模板化的)来自 smart_pointer<Derived>
至 smart_pointer<Base>
.
关于C++ 多重运算符=(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11883617/