c++ - 类运算符 '=' 定义

标签 c++

在 namespace MySpace 中,我创建了自定义字符串类:

namespace MySpace {
    const std::string bws = "hello";

    class string {
        public:
            std::string s ;
            string(void) :s(bws) {}
            string(const std::string & _s ) : s(bws) {};
            operator std::string & (void) {return s;}
    };
}

我确实将 MySpace::string f 分配给 std::string d

int main( int argc, char ** argv ) {
    MySpace::string f("ddd");
    std::string d=f;

    std::cout<<d<<std::endl;
}

为什么这有效?我还没有为 MySpace::string 定义运算符 =

为什么当我从 MySpace::string 中删除运算符 & 定义时它不起作用(行 operator std::string & (void) {返回 s;}) ?

& 不是 =

最佳答案

您已经实现了转换运算符:

operator std::string & (void) {return s;}

它基本上告诉编译器如何将 MySpace::string 转换为 std::string&

这里的&表示引用,您在这里重载的“operator”是“operator std::string”,而不是“运算符&”。 (这当然不是很迂腐)。

更多详情请参见:

http://en.cppreference.com/w/cpp/language/cast_operator

关于c++ - 类运算符 '=' 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25246368/

相关文章:

c++ - C++ 中的全卷积网络训练

c++ - 具有默认参数的 C++ 函数的多个声明

c++ - 我应该使用 GTK+ 还是 QT

c++ - 使用 <algorithm> sort 对自定义链表进行排序

c++ - C++将类拆分为多个文件。我指定类型时采用的显式类型int

c++ - 谁应该拥有迭代器、我的数据类或该类中的实际列表?

c++ - 如何在 C++ 中将文件保存到桌面?

c++ - 计算一个数的长度

c++ - 然后在 C++ 条件

c++ - 根据 QComboBox 的选择更改 QTableView 中的数据