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

关于 C++ 中 this 指针的使用~

S140131022 发布于 2014-10-26 16:36, 720 次点击
#include<iostream>
#include<string>
using namespace std;

class student
{
private:
    int num;
    string name;
    float grade;
public:
    student();
    void put(student *this);
};

student::student()
{
num=0;
name="none";
grade=0;
}

void student::put(student *this)
{
cout<<this->num<<endl;
cout<<this->name<<endl;
cout<<this->grade<<endl;
}

void main()
{
student stu;
stu.put(&stu);
}

本想用此程序来验证一下this指针的用法的,却无论如何都无法运行~请问哪儿出了错?
9 回复
#2
S1401310222014-10-26 17:53
#include<iostream>
using namespace std;

class time
{
private:
int hour;
int minu;
int seco;
public:
void put();
void set();
time(int a,int b,int c);
};
time::time(int a,int b,int c):hour(a),minu(b),seco(c){}

void time::set()
{
cin>>hour>>minu>>seco;
}

void time::put()
{
cout<<hour<<':'<<minu<<':'<<seco<<endl;
}

void main()
{
time t1(17,34,30);
time *const p;
p=&t1;

}
主函数中关于常指针又编译出错~我感觉没错呀~哎·....
#3
哆啦安梦2014-10-26 22:13
this指针是不能显式用作参数的
#4
哆啦安梦2014-10-26 22:15
常量必须进行初始化
time *const p = &t1;
#5
哆啦安梦2014-10-26 22:16
以下是引用哆啦安梦在2014-10-26 22:13:22的发言:

this指针是不能显式用作参数的

把put函数的声明、定义和主函数里的参数全去掉就行了
#6
qwe8851677592014-10-27 18:06
void put(student *this);你这一句中的 student * this相当于你又重新定义了一个名称为this的指针,(与int * p是一样样的)而不是类的this指针。
#7
沱游星空2014-10-30 13:40
time *const p;这句话顺序有问题!应该是const time *p;然后再初始化
#8
zcdjt2014-10-30 21:52
同上
#9
驽马吐了我2014-11-02 21:21
你们学的好难啊!我都看不懂。                                 y




类体外定义,类内加{}
#10
peixiao2014-11-15 12:32
this 指针是类固有的,无需重新定义;
1