C++ 多重运算符=()

标签 c++ operators implicit-conversion conversion-operator explicit-conversion

我正在编写一个 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/

相关文章:

c++ - 如何使用 C++ 和 Qt 将 QPixmap 保存为文件夹中的图片?

c++ - vector 对象请求的非标量类型转换

c++ - 为什么 x = x++;没有像我预期的那样工作?

time - 运算符(operator)突然不工作

arrays - 为什么二维数组的行为类似于一维指针数组而不是一维整数数组?

以void *和其他指针类型为参数的C++多态函数: is it considered ambiguous?

c++ - 我怎样才能让我的程序以秒为单位返回时钟一天中耗时?

c++ - 我怎样才能指向 vector 元素?

postgresql - 如何在 PostgreSQL 中为具有 int4range 值的 hstore 类型创建一个运算符

c - 如何从指针中减去字符数组?