Day:2018.1.15
● this指针的几点注意:
1.this指针无需操作者定义,是由编译器自动产生的;
2.同一个类的两个对象的this指针是指向各自对象的首地址的;
3.当成员函数的参数名与数据成员同名时,便是this指针大展拳脚的时候了;
4.this指针也是指针类型,所以在32位编译器下也占用4个基本的内存单元;
● this指针示例演示1
Array.cpp文件下(完整代码)
#include <iostream>
using namespace std;
class Test{
public:
Test(int num);
~Test();
void set(int num);
int get();
void print();
private:
int num;
};
Test::Test(int num){
//由于函数名与数据成员名相同,便是this指针出现的时候了!
this->num = num;
};
Test::~Test(){
};
void Test::set(int num){
//由于函数名与数据成员名相同,便是this指针出现的时候了!
this->num = num;
};
int Test::get(){
return num;
}
void Test::print(){
cout << "num = " << num << endl;
}
int main()
{
Test t(100);
cout << "num = " << t.get() << endl;
return 0;
}
编译结果:
this01.png
● this指针示例演示2
Array.cpp文件下(完整代码)
#include <iostream>
using namespace std;
class Test{
public:
Test(int num);
~Test();
void set(int num);
int get();
Test& print();
private:
int num;
};
Test::Test(int num){
this->num = num;
};
Test::~Test(){
};
void Test::set(int num){
this->num = num;
};
int Test::get(){
return num;
}
//此处注意区别:利用了&引用
Test& Test::print(){
cout << "num = " << num << endl;
return *this;
}
int main()
{
Test t(100);
t.print().set(50);
cout << "num = " << t.get() << endl;
return 0;
}
编译结果:
this02.png
网友评论