簡體   English   中英

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;
};

常量保護僅影響直接成員,在這種情況下,僅影響指針。 該對象之外的值(也稱為指向值)不受保護。

您必須決定是否將指示值視為自己或其他人。

您可以將成員Engine修改為const* ,這將使Car constp指向Engine對象:

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指向其他位置,它就是有效的。

由於在Accelerator未修改p (意味着它沒有指向其他內存地址),因此該程序有效。

當您將p指向其他位置時,程序將無法編譯:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM