| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 907 人关注过本帖
标题:这个this代表什么
只看楼主 加入收藏
hddgwxn586
Rank: 1
等 级:新手上路
帖 子:37
专家分:0
注 册:2017-5-18
结帖率:66.67%
收藏
已结贴  问题点数:10 回复次数:1 
这个this代表什么
这是网上一篇文章中的程序,运行正常。有一个语句看不懂,特来请教。
this->score = score;
这个this代表什么,整个程序中就只有一个,从哪里来的?
原文《深入解析C++中派生类的构造函数》  http://www.

程序如下:
#include<iostream>
using namespace std;
//基类
class People
{
protected:
  char *name;
  int age;
public:
  People(char*, int);//基类构造函数
};
People::People(char *name, int age): name(name), age(age){}

//派生类
class Student: public People
{
private:
  float score;
public:
  Student(char*, int, float);
  void display();
};
//调用了基类的构造函数
Student::Student(char *name, int age, float score): People(name, age)
{
 this->score = score;
}
void Student::display()
{
  cout<<name<<"的年龄是"<<age<<",成绩是"<<score<<endl;
}
int main()
{
  Student stu("小明", 16, 90.5);
  stu.display();
  return 0;
}
搜索更多相关主题的帖子: score name int age Student 
2017-07-17 15:31
GBH1
Rank: 7Rank: 7Rank: 7
等 级:黑侠
威 望:5
帖 子:112
专家分:510
注 册:2017-6-13
收藏
得分:10 
this->score = score;中this表示的是当前创建的实例。例如:Student stu("hahha",20,100.0);在执行构造函数时,this指的就是stu;

你也可以这样理解,在new一个新的实例时,系统会自动创建一个临时对象this,把你传入的值调用构造函数给this赋值。然后系统再把this的地址赋值给你创建的对象。
2017-07-17 15:58
快速回复:这个this代表什么
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017783 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved