- 类中可以包含引用成员,但必须在定义变量的时候默认初始化
- 引用作用域参数和返回值,避免内存占用
-
常引用等价于常对象
完整代码
1 #include <iostream> 2 using namespace std; 3 4 //声明类,提升作用域,只能作用于指针或者引用,不能是对象 5 //类中可以包含引用成员,必须要默认初始化 6 //引用作用域参数和返回值,避免内存占用 7 //常引用等价于常对象 8 class myclass; 9 10 myclass *p; 11 12 //错误 13 //myclass m; 14 15 //引用不会调用构造函数 16 void run(myclass &rmy) 17 { 18 19 } 20 21 class myclass 22 { 23 public: 24 int x =1; 25 int y = 2; 26 //引用初始化方式 27 //int &rx = x; 28 int &rx{ x }; 29 30 int &get(int &data) 31 { 32 return data; 33 } 34 35 void show() const 36 { 37 cout << "hello" << endl; 38 } 39 }; 40 41 void main() 42 { 43 int x = 3; 44 myclass my1; 45 my1.rx = x; 46 my1.rx = 5; 47 //常对象引用 48 const myclass &my2(my1); 49 my2.show(); 50 cin.get(); 51 }