Bil*_*ias 4 c++ qualifiers return-type visual-c++
实际上真是太棒了.有人可以用简单的英语解释为什么下面的部分工作与否?
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;
};
Run Code Online (Sandbox Code Playgroud)
您不能添加const多个深度本身不是指针的指针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
Run Code Online (Sandbox Code Playgroud)
制作指针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
Run Code Online (Sandbox Code Playgroud)