C++笔记(十四)——this指针

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37764129/article/details/83109582

问题描述:

        在point类中定义了一个input函数。当input函数的形参为与成员函数的实参相同,都是m_x,m_y时,pt.input(10, 10);的运行结果为5,5。错误原因见下例:

#include <iostream>
using namespace std;
class CPoint
{
public:
    int m_x;
    int m_y; 

        CPoint()
        {
            int m_x = 0;
            int m_y = 0;
        }

        CPoint(int a, int b)
        {
            m_x = a;
            m_y = b;
        }

        /*void input(int m_x, int m_y) //这里的m_x,m_y是形参
        {
            m_x = m_x;//形参与实参同名时,point类的成员变量m_x,m_y在input(int m_x,int m_y)这个函数中是不可见的,这个赋值实际上是形参传给了形参,故运行结果是5,5
            m_y = m_y;
        }*/
    
        //void input(int a, int b) //法一:形参的名字要与实参的名字不同
        //{
        //    m_x = a;
        //    m_y = b;
        //}
        
        void input(int m_x, int m_y) //不改名字的话,可用this指针
        {
            this->m_x = m_x;
            this->m_y = m_y;
        }
        
        void output()
        {
            cout << m_x << endl << m_y << endl;
        }
};

int main()
{
        CPoint pt(5, 5);
        pt.input(10, 10);
        pt.output();

    getchar();
    return 0;
}

this指针的原理:

         this指针是一个隐含的指针,它是指向对象本身的代表了对象的地址一个类所有的对象调用的成员函数都是同一个代码段,那么,成员函数又是怎么识别属于不同对象的数据成员呢?原来,在对象调用pt.input(10,10)时,成员函数除了接收2个实参外,还接收到了pt对象的地址,这个地址被一个隐含的形参this指针所获取,它等同于执行this =&pt。所有对数据成员的访问都隐含地被加上了前缀 this->。例如:x = 0;等价于this -> x=0;

猜你喜欢

转载自blog.csdn.net/qq_37764129/article/details/83109582