美文网首页
C++笔记(二)--this指针

C++笔记(二)--this指针

作者: 边牧哥哥sos | 来源:发表于2018-01-15 17:38 被阅读0次
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

相关文章

网友评论

      本文标题:C++笔记(二)--this指针

      本文链接:https://www.haomeiwen.com/subject/bejdoxtx.html