C++中const变量使用注意
2013-05-14 16:16
387 查看
例子1:
在windows下编译如上所示提示了两个错误,const变量必须在定义的时候进行初始化。
例子2:
C++有两种初始化方式,一种是直接初始化;另一种是复制初始化。
上面程序在Linux下还是出现了错误,
错误提示表明,没有对const Mike对象进行初始化。
改成如下方式:
这点在Linux下的表现和Windows下的表现不一样。
#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下的表现不一样。
相关文章推荐
- c++中const类型的使用与注意事项
- C++中全局变量的使用和注意事项
- C++ 构造函数使用 ":成员变量(形参)" 的形式给类里面成员变量赋值,如果成员变量和形参是指针,那么需要注意的事项
- c++中成员变量访问以及const的使用总结
- [C++]const、typedef联合使用注意
- [转]C++ const变量使用技巧总结
- [转]C++ const变量使用技巧总结
- 关于常见的变量修饰符: const, static, extern, register, auto 的详细解释,使用场合以及注意事项
- C++ const变量使用技巧总结
- 关于C/C++中静态本地变量的使用与数据类型修饰符const
- C++工程代码打包的dll在C#工程上使用注意点!变量对应关系与dll调用出错情况。
- c++全局变量使用中的一些注意事项
- C++中的'&'和const的使用注意事项!
- c++之const小结-使用注意
- C\C++: const的使用注意
- C++学习笔记(二):使用const、static类成员的注意事项
- C\C++: const的使用注意
- [转]C++ const变量使用技巧总结
- c语言const 变量使用注意点
- C++在使用Qt中SLOT宏需要注意的一个小细节