const 正确性和成员指针

const correctness and member pointers

我在 Accelerate 方法上有 const,但我可以调用 power 方法。他们是真正阻止这种情况的方法吗?

class Engine{
public:
    void Power(){
    }
};

class Car{
public:
    Car() : p(new Engine()){}

    void Accelerator() const{
        p->Power();
    } 
    private:
        Engine* p;
};

Const 保护仅影响直接成员,在本例中仅影响指针。此对象之外的值(也称为指向值)不受保护。

你要决定是把指向的值看成是你自己还是别人。

您可以将成员Engine修改为const*,这将使p指向的Engine对象指向Car const:

class Engine{
 public:
  void Power(){
  }
};

class Car{
 public:
  Car() : p(new Engine()){}

  void Accelerator() const{
      p->Power();
  } 
 private:
  Engine const* p;
};

这将不再编译:

test_const.cpp:12:9: error: member function 'Power' not viable: 'this' argument
      has type 'const Engine', but function is not marked const
        p->Power();
        ^
test_const.cpp:3:10: note: 'Power' declared here
    void Power(){
         ^

但这意味着 Car 的任何成员都不能修改 *p,这可能不是您想要的。请参阅@NathanOliver 的评论以获得更好的答案。

希望对您有所帮助。

对于Car,const方法是一种不修改Car成员变量的方法。

所以,只要Car::Accelerator不让p指向不同的位置,它就是有效的。

因为pAccelerator中没有被修改(意思是它没有指向不同的内存地址),所以程序是有效的。

当您将 p 指向不同的位置时,程序无法编译:

  void Accelerator() const {
        p= nullptr; //wrong
  }