【问题标题】:C++ overload operator= for different rhs types, at construction timeC++ 重载 operator= 在构造时用于不同的 rhs 类型
【发布时间】:2012-04-26 23:03:31
【问题描述】:

我编写了一个类Tag,它将标签保存为字符串并允许对其进行操作。为了便于使用,我将operator= 重载为类似字符串的类型。到目前为止我得到了什么:

Tag& Tag::operator=(const std::string& rhs)
{
    setTag(rhs);
    return *this;
}

Tag& Tag::operator=(const char* rhs)
{
     setTag(rhs);
     return *this;
}

(其中setTag()std::stringchar 重载)。大部分用法都包含在这个范围内:

 Tag tag1 = std::string("lala");
 Tag tag2;
 tag2 = std::string("lala2");
 Tag tag3;
 tag3 = "lala";

然而,最“基本”的人不会计算:

 Tag tag4 = "lala";

它给了我这个错误:

 conversion from 'const char [5]' to non-scalar type 'Tag' requested

我该如何解决这个问题?我做错了什么?

【问题讨论】:

    标签: c++ char operator-overloading


    【解决方案1】:

    最后一个不是operator=() - 您需要一个接受char const* 的构造函数。

    Tag(char const* s);
    

    【讨论】:

    • 详细地说,ClassName objVar = someValue; 调用单参数构造函数(相当于ClassName objVar (someValue);),而在对象创建后使用 = 调用 operator=
    • 这是我从不使用赋值语法进行构造的原因之一。此外,对于所有构造函数,我都放置了一个空格,例如 MyClass foo (a, b, c)MyClass ( ) 以提醒人们注意它也不是函数调用。 :-/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多