查了下,还真的有,不过你用编译器试试就可以知道了
In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose
value is the address of the object for which the function is called. The type of this in a member function
of a class X is X*. If the member function is declared const, the type of this is const X*, if the member
function is declared volatile, the type of this is volatile X*, and if the member function is
declared const volatile, the type of this is const volatile X*.
[测试代码]
#include <iostream>
using namespace std;
class Test
{
public:
void print();
void print_const() const;
};
void Test::print()
{
cout << this << endl;
this = 1;
}
void Test::print_const() const
{
cout << this << endl;
this = 1;
};
int main()
{
return 0;
}
[编译错误]
main.cpp(13) : error C2440: '=' : cannot convert from 'int' to 'Test *const '
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
main.cpp(19) : error C2440: '=' : cannot convert from 'int' to 'const Test *const '
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
VC6.0,2005都是一样,G++提示non-lvalue in assignment
正如C++标准草案中写的,the keyword this is a non-lvalue expression ,它是不能进行赋值的
回复 更多评论