创建对象后设置指向const对象的指针

时间:2013-01-27 18:50:42

标签: c++ pointers const

class a
{
    const std::string * ptr;
    void setPtr(const std::string & text)
    {
       ptr = &text; //it's wrong, I can set something to the pointer only at definition
    }
}

解决方案是什么?指向我的对象的指针必须是const(类a的对象不能修改它),但是我需要在运行时更改指针(它指向的位置)。

2 个答案:

答案 0 :(得分:2)

您可以使用当前代码执行此操作。这一行

const std::string * ptr;

表示ptr是指向const std::string的指针。 ptr本身并不是一成不变的,所以你可以改变它指向的内容。

请参阅this working demo

答案 1 :(得分:1)

您要么在示例中留下const

void setPtr(const std::string & text) const

或者您在setPtr

上致电const
const a* foo = something;
foo->setPtr(somestring);

基本上有三条规则:

您无法通过a成员函数修改非const const实例 您无法通过a指针或对它的引用来修改非常量const实例 您无法修改const a个实例。