c++指向const类成员的指针问题
我在使用 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
}
不幸的是,它不起作用,因为我仍然能够执行 quxBar->setX(100)
而没有编译错误。
也许我的方法是完全错误的,但使用当前的“技能”:)我不知道如何解决它。
预先感谢您的任何帮助和建议。
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 accidentally 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这不是您的实际代码,首先是因为它存在语法错误,其次是因为它实际上是正确的(大部分)。更具体地说,对于这段代码,
quxBar->setX(100);
将导致编译错误。然而,
quxBar->getX()
也会是一个编译错误,你需要告诉编译器可以在const对象上调用,你可以通过添加const
来做到这一点在函数签名的末尾:也许在您的实际代码中,您有
Bar* const quxBar
而不是Bar const* quxBar
;它们意味着两个不同的东西:前者是指向 Bar 的 const 指针,而后者是指向 const Bar 的指针。例如。在前面的情况下,只有指针本身不能修改,但它指向的对象可以。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 addingconst
at the end of the function signature:Perhaps in your actual code you had
Bar* const quxBar
instead ofBar 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.