C++進階--const和函數(const and functions)


// const和函數一起使用的情況
class Dog {
   int age;
   string name;
public:
   Dog() { age = 3; name = "dummy"; }
   
   // 參數為const,不能被修改
   void setAge(const int& a) { age = a; }  // 實參是常量時,調用此函數
   void setAge(int& a) { age = a; }    // 實參不是常量時,調用此函數
   void setAge(const int a) { age = a; } // 值傳遞使用const沒有意義
  
   
   // 返回值為const,不能被修改
   const string& getName() {return name;}
   const int getAge()  //值傳遞const沒有意義
   
   // const成員函數,成員數據不能被修改
   void printDogName() const { cout << name << "const" << endl; }    // 對象是常量時,調用此函數
   void printDogName() { cout << getName() << " non-const" << endl; }  // 對象不是常量時,調用此函數
};

int main() {

    // 常量和非常量的轉換
    // const_static去除變量的const屬性
    const Dog d2(8);
    d2.printDogName();  // const printDogName()
    const_cast<Dog&>(d2).printDogName() // non-const printDogName()

    // 使用static_cast加上const屬性
    Dog d(9);
    d.printDogName(); // invoke non-const printDogName()
    static_cast<const Dog&>(d).printDogName(); // invoke const printDogName()
   
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM