开发者

c++ pointer to const class member problem

开发者 https://www.devze.com 2023-01-19 12:00 出处:网络
I\'m having this problem with C++ classes. I would like to get pointer to myBar object and store it in quxBar. The reason is I would like to be able to check the value using quxBar->getX() but I wo

I'm having this problem with C++ classes. I would like to get pointer to myBar object and store it in quxBar. The reason is I would like to be able to check the value using quxBar->getX() but I would also like to prevent from acc开发者_开发百科identally modyfing it from Qux so I tried using 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
}

Unfortunatelly it doesn't work since I'm still able to perform quxBar->setX(100) with no compilation error.

Probably my approach is totally wrong, but using current "skills" :) I have no idea how to fix it.

Thanks in advance for any help and suggestions.


I don't think this is your actual code, firstly due to the syntax errors it has, and secondly due to the fact that it actually is correct (mostly). More specifically, with this piece of code, quxBar->setX(100); would result in compilation error.

However, quxBar->getX() would also be a compilation error, you need to tell the compiler that can be called on const objects, you do this by adding const at the end of the function signature:

int getX() const { return x; }

Perhaps in your actual code you had Bar* const quxBar instead of Bar const* quxBar; they mean two different things: The former is a const pointer to Bar, while the later is a pointer to const Bar. Eg. in the earlier case, only the pointer itself can't be modified, but the object it points to can.

0

精彩评论

暂无评论...
验证码 换一张
取 消