类运算符'='定义

时间:2014-08-11 15:00:42

标签: c++

在命名空间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) {return s;}时,它为什么不起作用?

&不是=

1 个答案:

答案 0 :(得分:2)

您已实施转换运算符:

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

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

&表示此处的引用,&#34; operator&#34;你在这里超载是&#34; operator std::string&#34;,而不是&#34; operator &&#34;。 (这当然不是很迂腐)。

有关详细信息,请参阅:

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

相关问题