当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++ this指针的理解和作用

C++ this指针的理解和作用

2019年11月29日  | 移动技术网IT编程  | 我要评论

沈志明个人资料,浩劫妙冤家,龙木阁

01 c++ 程序到 c 程序的翻译

要想理解 c++ 的 this 指针,我们先把下面的 c++ 代码转换成 c 的代码

class car 
{
public:
    int m_price;         // 成员变量
    void setprice(int p) // 成员函数
    {
        m_price = p; 
    }
};

int main()
{
    car car;
    car.setprice(20000); // 给car对象m_price成员变量赋值
    
    return 0;
}

c 语言是没有类定义的class关键词,但是有跟class类似的定义,那就是结构体struct

m_price变量是car类的成员变量,那么我们可以把car类和成员变量翻译成如下的 c 代码:

// 结构体car
struct car
{
    // price变量是属于car结构体这个域里的变量
    int price;  
};

setprice函数是car类的成员函数,但是 c 程序里是没有成员函数这种概念的,所以只能把成员函数翻译成全局的函数:

// 参数1:结构体car的指针
// 参数2:要设置的价格变量
void setprice(struct car* this, int p)
{ 
    this->price = p;  // 将传入的car结构体的price变量赋值
}

为什么要加个 this 的指针呢?我们继续往下看。

在这里我们把上面main函数下面的 c++ 程序翻译 c 程序是这样的:

int main() 
{
    struct car car;
    setprice( &car, 20000);
    return 0;
}

所以最终把上述的 c++程序 转换成c 程序的代码如下:

struct car
{
    int price;  
};


void setprice(struct car* this, int p)
{ 
    this->price = p; 
}

int main() 
{
    struct car car;
    setprice( &car, 20000); // 给car结构体的price变量赋值
    return 0;
}

02 this指针的作用

其作用就是指向成员函数所作用的对象,
所以非静态成员函数中可以直接使用 this 来代表指向该函数作用的对象的指针。

#include <iostream>

class car 
{
public:
    int m_price;
    
    void printprice()
    {
        std::cout << m_price << std::endl;  
    }
    
    void setprice(int p)
    {
        this->m_price = p; // 等价于 m_price = p;
        this->printprice();// 等价于 printprice();
    }
    
    car getcar()
    {
        return *this; // 返回该函数作用的对象
    }
};

int main(void)
{
    car car1, car2;
    car1.setprice(20000);
    
    // getcar()成员函数返回所作用的car1对象,所把返回的car1赋值给了car2
    car2 = car1.getcar(); 
    car2.printprice();   
    
    return 0;
}

输出结果:

20000
20000

接下来我们下面的代码,你觉得输出结果是什么呢?会出错吗?

class a
{
    int i;
    public:
    void hello() { cout << "hello" << endl; }
};

int main()
{
    a * p = null;
    p->hello(); //结果会怎样?
}

答案是正常输出hello,你可能会好奇明明 p 指针是空的,不应该是会程序奔溃吗?别着急,我们先把上面的代码转换c程序,就能理解为什么能正常运行了。

void hello() { cout << "hello" << endl; } 
# 成员函数相当于如下形式:
void hello(a * this ) { cout << "hello" << endl; }

p->hello(); 
# 执行hello()形式相当于:
hello(p);

所以,实际上每个成员函数的第一个参数默认都有个指向对象的 this 指针,上述情况下如果该指向的对象是空,相当于成员函数的第一个参数是null,那么只要成员函数没有使用到成员变量,也是可以正常执行。

下面这份代码执行时,就会奔溃了,因为this指针是空的,使用了 空的指针指向了成员变量i,程序就会奔溃。

class a
{
    int i;
public:
    void hello() { cout << i << "hello" << endl; }
    // ->> void hello(a * this ) { cout << this->i << "hello" << endl; }
};
int main()
{
    a * p = null;
    p->hello(); //  ->> hello(p); 
}

03 this指针和静态成员函数

静态成员函数是不能使用 this 指针,因为静态成员函数相当于是共享的变量,不属于某个对象的变量。


04 小结

  • 通过将c++程序翻译成c程序的方式,来理解 this 指针,其作用就是指向非静态成员函数所作用的对象,每个成员函数的第一个参数实际上都是有个默认 this 指针参数。

  • 静态成员函数是无法使用this指针,

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网