C++ : 自动常量?
当我编译此代码时:
class DecoratedString
{
private:
std::string m_String;
public:
// ... constructs, destructors, etc
std::string& ToString() const
{
return m_String;
}
}
我从 g++ 中收到以下错误:来自类型 'const std::string' 的表达式的类型 'std::string&" 的引用初始化无效
。
为什么m_String 被视为 const 吗?编译器不应该在这里简单地创建一个引用吗?
编辑:
此外,我应该做什么才能让这个函数充当到大多数情况下工作的字符串的转换?情况? 我将函数设置为 const,因为它不会修改内部字符串...也许我只需要让它返回一个副本...
编辑:好的...使其返回一个副本有效。
When I compile this code:
class DecoratedString
{
private:
std::string m_String;
public:
// ... constructs, destructors, etc
std::string& ToString() const
{
return m_String;
}
}
I get the following error from g++: invalid initialization of reference of type 'std::string&" from expression of type 'const std::string'
.
Why is m_String being treated as const? Shouldn't the compiler simply create a reference here?
EDIT:
Further, what should I do to get this function to act as a conversion to a string that will work in most cases? I made the function const, as it doesn't modify the internal string... maybe I just need to make it return a copy...
EDIT: Okay... making it return a copy worked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
m_String
被视为 const,因为它是作为 const 访问的,并且
this
是 const,因为成员函数ToString()
是 const 限定的。m_String
is treated as const because it is accessed asand
this
is const because the member function,ToString()
is const-qualified.此时,
m_String
是const
,因为您已选择将方法声明为const
(这当然使得所有数据实例成员也是 const)——如果您需要绕过该特定数据成员,您可以选择显式使其可变
。m_String
isconst
at that point because you've chosen to declare the method asconst
(which of course makes all data instance members const, too) -- if you need to bypass that for that specific data member, you could choose to explicitly make itmutable
.因为该方法是 const(
std::string&ToString() const
中的const
)。 Const 方法将this
视为const
对象,并将其成员视为const
对象。Because the method is const (the
const
instd::string& ToString() const
). Const method seethis
as aconst
object, and its memebers asconst
objects, too.因为您通过常量
this
访问m_String
(该方法是const
)。Because you access
m_String
through a constantthis
(the method isconst
).