在函数中使用const指向类

mik*_*ike 2 c++ const shared-ptr

我在代码中大量使用std :: shared_ptr.我有一些函数,我想从MyClass使用"this"调用,所以已声明这些函数(例如)

int AnotherClass::foo(const MyClass *obj)
{
} 
Run Code Online (Sandbox Code Playgroud)

我希望const明确表示obj不会被改变,因为我传递了一个原始指针.但是,我有内心

int AnotherClass::foo(const MyClass *obj)
{
    int number = obj->num_points()-1;
}
Run Code Online (Sandbox Code Playgroud)

并且我的编译器抱怨"该对象具有与成员函数不兼容的类型限定符".num_points是在标头中声明和定义的简单get函数:

class MyClass {
public:
  ...
  int num_points(){return _points.size();}
  ...
private:
  std::vector<MyPoint> _points;
};
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?显然我可以摆脱foo中的const要求,但我喜欢它强加的刚性.提前谢谢了!

jro*_*rok 10

使该成员功能const:

int num_points() const // <---
{
    return _points.size();
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以在const对象上调用它.进入habbit以符合这个限定每个不改变对象状态的功能.


Ker*_* SB 6

也声明num_points为const:

int num_points() const
{
    return _points.size();
}
Run Code Online (Sandbox Code Playgroud)