#include <iostream> using namespace std; class MyClass { public: int GetValue() const ; int GetValue() { return x + y; } int GetMax() { return x > y ? x : y; } int GetMin() const { //p += 3;//错误,常函数成员不能更新数据 return x < p ? x : y; //正确,p可以被使用 } static void Display(const int &r) { cout << "所引用的对象为" << r << endl; } static void Display_no_const(int &r) { cout << "所引用的对象为" << r << endl; } MyClass(int a, int b) :x(a), y(b) //构造函数只能通过列表初始化的形式对常量成员进行初始化 { cout << z << "<<<<"; } const int z = 3;//定义时进行初始化,不需要在构造函数中进行初始化 private: int p = 1; const int x, y; }; int MyClass::GetValue() const { return x * y; } int main(void) { const MyClass m1(2, 3); MyClass m2(5, 6); const int i = 0; int j = 5; // m1.z++; 错误,不能给常量赋值 cout << m1.GetValue() << "<- first one" << endl; cout << m2.GetValue() << "<- second one\n"; //m1.GetMax(); //错误,不能用常对象调用非常函数成员 cout << m1.GetMin() << endl; //cout << m1.z; MyClass::Display(i); MyClass::Display(j); //可以从“int”转换为“const int &” // MyClass::Display_no_const(i); //错误, 无法将参数 i 从“const int”转换为“int &” return 0; }
/*常量的总结: 1.常数据类型(const int i = 0;): 定义时就要初始化。 2.类中的 常对象(const MyClass m1(2, 3);):常对象一旦被定义即表示对象的成员也变成常类型, 即不能对其修改 若要修改需要加关键字 mutable 修饰 3.类中的 常数据成员:在类的实例化对象时,由于定义类时的数据成员为常数据类型,故需要在实例化对象时进行初始化 常数据成员,即通过构造函数初始化列表的方式实现,也可在定义类的常数据成员时进行初始化。常数据成员一样也不可以修改。 4.类中的 常函数成员:可以实现函数的重载(如:GetValue()的重载); 常成员函数可以修改静态数据成员,因为静态数据不属于对象,而是类的属性。 还可以修改全局变量,其他对象的成员变量,被 mutable 修饰的成员变量; 不能更新任何数据成员; 不能调用非常函数成员; 5.常引用(const int &r):常引用所引用的对象不能被修改; */