c++ - 想要分配 std::string 但编译器认为是 bool

标签 c++ string methods std assign

<分区>

我假装编写一个可以充当变体类型的类。 一切正常,但是当我尝试分配一个字符串时,调用的方法是使用 bool 作为参数的方法:

class value_t {
public:
    value_t operator=(const int& integer) {
        std::cout<<"integer"<<std::endl;
        return *this;
    };
    value_t operator=(const std::string& str) {
        std::cout<<"string"<<std::endl;
        return *this;
    };
    value_t operator=(const bool& boolean) {
        std::cout<<"boolean"<<std::endl;
        return *this;
    };

};

value_t val;
val = "Hola mundo";

输出是:

boolean

为什么不调用字符串赋值运算符方法?

谢谢

最佳答案

"Hola mundo" 这样的字符串文字是一个 const char [],它会退化为 const char *

语言标准定义了从任何指针到 bool 的隐式转换。

编译器选择您的 bool 运算符作为更好的选择,因为调用您的 std::string 运算符需要编译器构造一个临时的 std::string 对象,而调用 bool 运算符则不会。

要执行您想要的操作,请为 const char * 添加另一个运算符,以便编译器根本不需要转换(它可以选择调用 std::string 运算符(如果需要)):

value_t operator=(const char* str) {
    std::cout << "char*" << std::endl;
    return *this;
};

value_t operator=(const char* str) {
    return operator=(std::string(str));
};

否则,你必须显式地传入一个std::string:

val = std::string("Hola mundo");

附带说明一下,您的运算符应该返回一个 value_t& 引用。

关于c++ - 想要分配 std::string 但编译器认为是 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764713/

相关文章:

java - 调用 Java 方法时出错

c++ - 什么是前向声明

c++ - 运行 QFileDialog::getOpenFileName 而不需要单独的事件循环?

regex - 如何在两个图案之间打印线条?

java - 将字符串拆分为单个单词并忽略其他所有内容

java - 在java中传递数组

c++ - 你能用英语尽可能简单地解释什么是复制构造函数以及我什么时候需要使用它吗

c++ - C++中长表达式的优化

objective-c - 如何查看字符串是否包含子字符串(objective-c)

c# - 文件阅读器卡住我的程序