我想要一个可以接受来自 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/