4

其实是地狱。有人可以用简单的英语解释为什么以下部分有效吗?

class Hey;

class Bitmap {

public:
    const Hey* const& getHey() { return hey; }; // works
    const Hey* & getHey2() { return hey; }; // error C2440: 'return' : cannot convert from 'Hey *' to 'const Hey *&'

private:
    Hey* hey;
};
4

3 回答 3

8

您不能const向指针添加多于一种类型的 deep 而不是它本身const,因为这样您就可以将变量的地址填充const到非const指针中。考虑:

char c;
char* p = &c;
const char* cp = p; // ok, only one type deep
const char x;
cp = &x; // ok
const char*& r = p; // fail, because...
r = cp; // ok
*p = 5; // ok, would overwrite a const variable if binding r to p were allowed

制作指针const以不同的方式防止这种灾难。继续示例:

const char* const& cr = p; // ok
cr = cp; // fail, cr is const, saving us from...
*p = 5; // would overwrite a const variable if cr = cp were allowed
于 2011-02-08T13:53:01.133 回答
1

const 引用可以初始化为不同类型的对象或右值,例如常量表达式:

  const int i = 42;
  //  legal for const references only
  const int &r = i;

相同的初始化对于非常量引用是不合法的。

您正在尝试使用 const 表达式初始化引用。const 表达式是右值。const 引用可以用右值初始化,而非 const 不能。

编辑:关于 rvalues 和 lvalues 您可以在weakipedia中阅读。

于 2011-02-08T14:08:07.443 回答
0

编译器没有将“Hey*”和“const Hey*”视为相同,因此它不想转换引用而他转换 const 引用(类似于参数转换)

于 2011-02-08T14:02:04.543 回答