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()
       
    }
    
  • 相关阅读:
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第六周&java实验报告四
    第五周课程总结&试验报告(三)
    第四周作业
    2019春总结作业
    第二周基础作业
    第三周作业
    2019期末总结
    第十四周课程总结 & 实验报告
  • 原文地址:https://www.cnblogs.com/logchen/p/10164841.html
Copyright © 2011-2022 走看看