- 返回引用时,遇到了了类型强转的问题
double test = 1.12;
int& func()
{
return (int)test;
}
// 编译报错:invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
这是因为(int)test 会得到一个临时变量,该临时变量属于rvalue,不可以寻址,而引用本身属于取地址,因此会报错,必须写成:
return (int&)test;
- 返回常引用的问题
class test {
private:
int a = 88;
public:
// 注意这里不可以写成int& get() const
// 因为如果这样,通过调用get()函数即可以修改a的值了,这样与后面的const相违背
const int& get() const
{
return a;
}
};
int main()
{
test t;
// 这里并不存在const转为非const的报错,因为t.get()首先会创建一个局部变量,然后
// 将局部变量赋给y,所以不会报错
int y = t.get();
}