返回只读双指针
我想要一个成员变量,它是一个双指针。双指针指向的对象不得从类外部修改。
我的以下尝试产生了 “从 'std::string**' 到 'const std::string**' 的转换无效”
class C{
public:
const std::string **getPrivate(){
return myPrivate;
}
private:
std::string **myPrivate;
};
- 如果我只使用一个简单的指针
std::string,为什么相同的构造有效*myPrivate
如何返回只读双指针?
执行显式强制转换
return (const std::string**) myPrivate
是一种好的风格吗?
I want to a member variable, which is a double pointer. The object, the double pointer points to shall not be modified from outside the class.
My following try yields an
"invalid conversion from ‘std::string**’ to ‘const std::string**’"
class C{
public:
const std::string **getPrivate(){
return myPrivate;
}
private:
std::string **myPrivate;
};
- Why is the same construct valid if i use just a simple pointer
std::string *myPrivate
What can i do to return a read-only double pointer?
Is it good style to do an explicit cast
return (const std::string**) myPrivate
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
const std::string ** 的问题在于它允许调用者修改未声明为 const 的指针之一。这使得指针和字符串类本身都成为常量。
Try this:
The trouble with const std::string ** is that it allows the caller to modify one of the pointers, which isn't declared as const. This makes both the pointer and the string class itself const.
如果您想真正挑剔:
If you want to be really picky :
在 c++ 中,在极少数情况下确实需要原始指针(对于双指针来说更少),而您的情况似乎不是其中之一。正确的方法是返回一个值或引用,如下所示:
There are very rare cases in c++ when a raw pointer (even less for a double pointer) is really needed, and your case doesn't seams to be one of them. A proper way would be to return a value or a reference, like this :