C++ 类中声明并定义静态常量字符串数组属性


#include <iostream>
using namespace std;

 

class Person {
   public:
    int id = 200;
    string name = "qiumc";
    // 在类中声明并定义静态常量字符串数组
    // char*改为string类型会报错
    // 没有constexpr的修饰会报错
    static constexpr const char* arrayAttribute[] = {"Hello123", "World123"};
};

 

int main(int argc, char const* argv[]) {
    Person p;
  
    // cout << Person::arrayAttribute << endl; 直接这种写法会报错,这是因为constexpr是在编译的时候求值,编译后根本就没有Person::arrayAttribute这个符号
    cout << Person::arrayAttribute[0] << endl;
    cout << Person::arrayAttribute[1] << endl;
    return 0;
}
 
 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM