c ++指向const类成员问题的指针

Moo*_*min 1 c++ pointers pointer-to-member

我在使用C++类时遇到了这个问题.我想获得指向myBar对象的指针并存储它quxBar.原因是我希望能够检查使用的值,quxBar->getX()但我也想防止从Qux中意外地使用它,所以我尝试使用Bar const*.

class Bar
{
private:
    int x;
public:
    void setX(int X) { x = X; };
    int getX(){ return x };
}

class Foo
{
private:
    Bar *myBar;
public: 
    Bar const* getPointerToBar(){ return myBar; };            
}

class Qux
{
    void myMethod();
    Bar const* quxBar;
    Foo *mainFoo;    
}

void Qux::myMethod()
{
    quxBar = mainFoo->getPointerToBar();
    std::cout << quxBar->getX();
    quxBar->setX(100);  // HERE!!!
    std::cout << quxBar->getX(); // returns 100
}
Run Code Online (Sandbox Code Playgroud)

不幸的是它不起作用,因为我仍然能够执行quxBar->setX(100)没有编译错误.

可能我的方法是完全错误的,但使用当前的"技能":)我不知道如何解决它.

提前感谢您的任何帮助和建议.

rek*_*o_t 7

我不认为这是你的实际代码,首先是由于它有语法错误,其次是因为它实际上是正确的(大多数情况下).更具体地说,使用这段代码quxBar->setX(100);会导致编译错误.

但是,quxBar->getX()也是一个编译错误,你需要告诉编译器可以在const对象上调用,你可以通过const在函数签名的末尾添加:

int getX() const { return x; }
Run Code Online (Sandbox Code Playgroud)

也许在您的实际代码中,Bar* const quxBar而不是Bar const* quxBar; 它们意味着两个不同的东西:前者是指向 Bar 的const指针,而后者是指向const Bar的指针.例如.在前面的情况下,只有指针本身不能被修改,但它指向的对象可以.