c++ - C++ 中 int 和 char 的重载运算符

标签 c++ char operator-overloading

我想要一个可以接受来自 int 和 int 以及字符串文字的赋值的类。事实证明,字符串文字必须是 char[] 类型。我实际上有很多数据类型都被赋值运算符成功采用。但是编译器会混淆这两者。我知道 char 可以与 int 互换,我经常用它来进行快速的 ascii 比较。我想知道的是,是否有办法让编译器停止尝试将字符串文字发送到重载运算符的 int 版本。其他类型都没有这个问题,只有这两个会混淆。

    myDataType& operator = (int Right);
    myDataType& operator = (const char &Right);

当我尝试时:

myDataType Test;

Test = "Hello World.";

编译器试图将字符串文字解释为 int 并抛出此错误:错误:从‘const char*’到‘int’的无效转换[-fpermissive]

谢谢。

最佳答案

如果字符串必须是 char[] 类型,那么您必须在签名中包含 []*

myDataType& operator = (int Right);
myDataType& operator = (const char *Right);

myDataType& operator = (int Right);
template<size_t N>
myDataType& operator = (const char (&Right)[N]);

但是,因为这是 C++,实际使用 string

可能更简单
myDataType& operator = (int Right);
myDataType& operator = (std::string Right);

关于c++ - C++ 中 int 和 char 的重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875707/

相关文章:

c++ - 将可选的隐式转换为 bool 值?

c++ - 'Figure::Figure()' 的原型(prototype)与类 'Figure' 中的任何一个都不匹配

c++ - 将 Objective-C 应用程序链接到 C++ 静态库

c++ - 调用者保存的寄存器和被调用者保存的寄存器有什么区别?

c++ - 可移植代码 - 每个字符的位数

c++ - 将无符号字符数组转换为 float 组

c++ - 用 C++ 字符从字母到数字

java - Jexl3 中自定义类的运算符重载/定义

c++ - 为底层容器不存储真实对象的迭代器重载 operator->

c++ - 运算符重载代码编译错误,模板参数推导/替换失败