随笔-34  评论-108  文章-0  trackbacks-0
    在一个非静态的成员里面,this关键字就是一个指针,指向该函数的这次调用所针对的那个对象。
    在类X的非const成员函数里,this的类型就是X*,然而this并不是一个常规变量,不能获取this的地址或者给它赋值。
    在类X的const成员函数里,this的类型就是const X*,以防止对这个对象本身的修改。
posted on 2007-02-10 11:12 探丫头 阅读(2348) 评论(4)  编辑 收藏 引用 所属分类: 编程语言——C++

评论:
# re: this指针 2007-02-10 11:19 | nono
获取this指针的地址是可以的;)
而且在类X的非const成员函数里,this的类型应该是X* const,所以可以修改this说指向的地址的值的内容,而不能修改自身;
在类X的const成员函数里,则是const X * const所以两边都不能修改  回复  更多评论
  
# re: this指针 2007-02-10 13:01 | 平凡小草
C++标准的确就是我文章中这样说的  回复  更多评论
  
# re: this指针 2007-02-10 14:42 | nono
查了下,还真的有,不过你用编译器试试就可以知道了
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 ,它是不能进行赋值的  回复  更多评论
  
# re: this指针 2007-02-10 14:47 | 平凡小草
@nono
谢谢你的指导,的确如你所说  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理