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()
   
}

猜你喜欢

转载自www.cnblogs.com/logchen/p/10164841.html