你有没有恨它
class Foobar {
public:
Something& getSomething(int index) {
// big, non-trivial chunk of code...
return something;
}
const Something& getSomething(int index) const {
// big, non-trivial chunk of code...
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
我们无法使用另一个方法实现这两种方法,因为您无法const从const版本中调用非版本(编译器错误).演员将被要求const从非const一个版本调用该版本.
有没有一个真正优雅的解决方案,如果没有,最接近一个?
#include <iostream>
using namespace std;
int main() {
const int N = 22;
int * pN = const_cast<int*>(&N);
*pN = 33;
cout << N << '\t' << &N << endl;
cout << *pN << '\t' << pN << endl;
}
Run Code Online (Sandbox Code Playgroud)
22 0x22ff74
33 0x22ff74
为什么同一地址有两个不同的值?
int main()
{
const int ia = 10;
int *pia = const_cast<int*>(&ia);
*pia = 5;
std::cout << &ia << "\t" << pia <<endl;
std::cout << ia << "\t" << *pia <<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0x28fef4 0x28fef4
10 5
Run Code Online (Sandbox Code Playgroud)
*pia并ia具有相同的地址,但它们具有不同的值.我的目的是用来const_cast修改一个常量值,但结果显示它不起作用.
有谁知道为什么?