zoukankan      html  css  js  c++  java
  • C++中const变量使用注意

    例子1:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Student
    {
    public:
        Student* operator&() {cout << "Get addr" << endl; return this;}
        Student const* operator&() const {cout << "Get const addr" << endl; return this;}
    };
    
    // error C2734: “number”: 如果不是外部的,则必须初始化常量对象
    const int number;
    
    int main(int argc, char** argv)
    {
        Student Jack;
        &Jack;
    
        const Student Mike;
        &Mike;
    
        // error C2734: “ch”: 如果不是外部的,则必须初始化常量对象
        const char ch;
    
        return 0;
    }

     在windows下编译如上所示提示了两个错误,const变量必须在定义的时候进行初始化。

    例子2:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Student
    {
    public:
        Student* operator&() {cout << "Get addr" << endl; return this;}
        Student const* operator&() const {cout << "Get const addr" << endl; return this;}
    };
    
    // const int number = 2; 复制初始化是最常用的方式
    const int number(2);  // 直接初始化
    
    int main(int argc, char** argv)
    {
        Student Jack;
        &Jack;
    
        const Student Mike;
        &Mike;
    
        // const char ch = 'w'; 复制初始化是最常用的方式
        const char ch('w');  // 直接初始化
    
        return 0;
    }

    C++有两种初始化方式,一种是直接初始化;另一种是复制初始化。

    上面程序在Linux下还是出现了错误,

    错误提示表明,没有对const Mike对象进行初始化。

    改成如下方式:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Student
    {
    public:
        Student() {}
        ~Student() {}
        Student* operator&() {cout << "Get addr" << endl; return this;}
        Student const* operator&() const {cout << "Get const addr" << endl; return this;}
    };
    
    // const int number = 2; 复制初始化是最常用的方式
    const
    int number(2); // 直接初始化 int main(int argc, char** argv) { Student Jack; &Jack; const Student Mike; &Mike; // const char ch = 'w'; 复制初始化是最常用的方式 const char ch('w'); // 直接初始化 return 0; }

    这点在Linux下的表现和Windows下的表现不一样。

  • 相关阅读:
    独木桥上的羊和狼
    Mac 如何截屏(快捷键)
    Mac 版 QQ 可直接访问 iPhone 的相册 ?!
    年轻时就该追求绚烂之极
    Java-HTTP连接时如何使用代理(二)—— Proxy类方式
    Java-HTTP连接时如何使用代理(一)—— System.Property方式
    妻子的空位——韩国一位单亲爸爸的心声
    不得不
    为了避免结束,你避免了一切开始
    iPhone —— 如何自制铃声(图文)
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3077998.html
Copyright © 2011-2022 走看看