1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> using namespace std; class MyClass { private: int * a; int b; public: MyClass() { a = new int; } ~MyClass() { delete a; } int & geta(void) const { return *a; } // good? int & getb(void) const { return b; } // obviously bad }; int main() { return 0; } |
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmNsYXNzIE15Q2xhc3MKewogIHByaXZhdGU6CiAgICBpbnQgKiBhOwogICAgaW50IGI7CiAgcHVibGljOgogICAgTXlDbGFzcygpIHsgYSA9IG5ldyBpbnQ7IH0KICAgIH5NeUNsYXNzKCkgeyBkZWxldGUgYTsgfQoKICAgIGludCAmIGdldGEodm9pZCkgY29uc3QgeyByZXR1cm4gKmE7IH0gLy8gZ29vZD8KICAgIGludCAmIGdldGIodm9pZCkgY29uc3QgeyByZXR1cm4gYjsgfSAgLy8gb2J2aW91c2x5IGJhZAp9OwoKaW50IG1haW4oKSB7CglyZXR1cm4gMDsKfQ==
prog.cpp: In member function ‘int& MyClass::getb() const’: prog.cpp:15: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’
-
result: Compilation error (maybe you wish to see an example for C++ 4.7.2)


