zoukankan      html  css  js  c++  java
  • 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()
       
    }
    
  • 相关阅读:
    文件进阶
    文件及文件操作
    字符编码
    集合
    数据类型之字典
    数据类型之列表,元组
    数据类型之数字,字符串
    for 循环语句
    while 循环语句
    深浅拷贝
  • 原文地址:https://www.cnblogs.com/logchen/p/10164841.html
Copyright © 2011-2022 走看看