代码之家  ›  专栏  ›  技术社区  ›  J. Polfer

C++:自动const?

  •  2
  • J. Polfer  · 技术社区  · 14 年前

    当我编译这段代码时:

    class DecoratedString
    {
    private:
        std::string m_String;
    public:
         // ... constructs, destructors, etc
         std::string& ToString() const
         {
             return m_String;
         }
    }
    

    我从g++得到以下错误: invalid initialization of reference of type 'std::string&" from expression of type 'const std::string' .

    为什么m\u字符串被视为常量?编译器不应该在这里创建一个引用吗?

    编辑:

    我应该怎么做才能让这个函数转换成在大多数情况下都能工作的字符串? 我做了const函数,因为它不修改内部字符串。。。也许我只需要让它返回一个副本。。。

    编辑:好的。。。使它返回一个副本工作。

    4 回复  |  直到 14 年前
        1
  •  9
  •   James McNellis    14 年前

    m_String 被视为常量,因为它作为

    this->m_String
    

    this ToString() 是合格的。

        2
  •  3
  •   Alex Martelli    14 年前

    m_String const 因为你选择了 方法 作为 常数 mutable

        3
  •  1
  •   jpalecek    14 年前

    因为方法是const(the const 在里面 std::string& ToString() const ). 常量方法参见 this 作为一个 常数 对象及其成员 常数 物体也是。

        4
  •  1
  •   doublep    14 年前

    因为你可以访问 m_String 通过常数 this const ).

    推荐文章