成员变量是引用类型
- 不能有默认构造函数必须提供构造函数
- 构造函数的形参必须为引用类型
- 初始化必须在成员初始化链表内完成
const类型也必须在初始化列表中初始化,不可以在构造函数体内初始化
#include <iostream>
using namespace std;
class Ref
{
public:
// 构造函数形参为传值,不能保证正确性
// Ref (int target) :myref(target) {
// cout << "Ref constructor" << endl;
// }
// 函数体对引用赋值,编译错误:引用未初始化
// Ref (int &target) {
// myref = target;
// cout << "Ref constructor" << endl;
// }
// 如果成员为变量为引用类型,那么构造函数的参数为应用类型
// 引用必须在成员初始化链表里面初始化,不能在函数体里面初始化
// 在函数体里面修改myref,相当于赋值,显然引用不能赋值
Ref (int &target) :myref(target) {
cout << "Ref constructor" << endl;
}
void printRef() {
cout << "myref is: " << myref << endl;
}
virtual ~Ref () {}
private:
int &myref;
/* data */
};
int main(int argc, char *argv[])
{
int a = 20;
Ref r(a);
r.printRef();
int &b = a;
Ref r1(b);
r1.printRef();
// error:引用定义时必须初始化
// int &c;
return 0;
}