注册 登录
编程论坛 C++教室

有关this指针的知识,不太明白

lindayanglong 发布于 2008-08-29 15:32, 1031 次点击
下面是一段有关this指针的程序,我不理解x& X::Set(char *pc)
这样到底是什么意思,为什么要这样 请高手指教


#include<iostream>
#include<string>
using namespace std;
struct x
{
private:
    int len;
    char *ptr;
public:
    int GetLen()
    {
        return len;
    }
    char * Getptr()
    {
        return ptr;
    }
    X& Set(char *);
    X& Cat(char *);
    void print();
};
x& X::Set(char *pc)
{
    len=strlen(pc);
    ptr=new char[len];
    strcpy(ptr,pc);
    return *this;
}

x& X::Cat(char *pc)
{
    len+=strlen(pc);
    strcat(ptr,pc);
    return *this;
}

x& X::copy(X& x)
{
    Set(x.Getptr());
    return *this;
}
6 回复
#2
p1s2008-08-29 17:30
x& X::Set(char *pc)
{
    len=strlen(pc);//记录len为字符串pc的长度
    ptr=new char[len];//新辟堆内存空间给ptr
    strcpy(ptr,pc);//将字符串pc的内容复制给ptr
    return *this;//将调用Set成员函数的这个对象作为结果返回
}
#3
mcyrdb2008-08-29 22:06
x& X::Set(char *pc)
x& 是返回值结构体x的引用
因为声明和定义是分开的 所以有X::(应该是x::吧)
#4
scauhj2008-08-29 23:38
struct是类的一种,在这个程序当中函数的定义是在类的外面,所以要用::指示类的作用域,x& 是函数返回的类型引用
#5
zhuerhua2008-09-01 11:25
参考一楼回答.
#6
zzt_4282008-09-30 12:01
this 指针指向调用成员函数的对象本身.
#7
newyj2008-09-30 20:28
这样主要是可以 在调用时 写成一列
举个例子:
set().Cat();
1