C++——this指針

this指針的出現(xiàn)是因?yàn)樵谠缙跊](méi)有c++編譯器,c++程序只能使用c語(yǔ)言的編譯器進(jìn)行編譯。所以c++的程序先需要翻譯為程序。

C++程序如下:

class Demo

{

int id;

public :

Demo(int i)

{

id = i;

cout << "id = " << id << "創(chuàng)建" << endl;

}

~Demo()

{

cout << "id =" << id << "釋放" << endl;

}

void Func_a(int i)

{

id = i;

cout << "類(lèi)函數(shù)" << id << endl;

}

};

int main()

{

Demo A(1);

A.Func_a(20);

return 0;

}

翻譯后的C程序:

#include "pch.h"

#include <iostream>

using namespace std;

struct Demo

{

int id;

};

void Func_a(struct Demo * this, int i)

{

cout << "類(lèi)函數(shù)" << i << endl;

}

int mian()

{

struct Demo A;

Func_a(&A,20);

return? 0;

}

this指針的作用就是指向成員函數(shù)所作用的對(duì)象。

class shi_shu

{

public:

int shi_bu, xv_bu;

shi_shu();

shi_shu(int i,int j);

~shi_shu();

shi_shu add_one()

{

this->shi_bu++;

this->xv_bu++;

return *this;

}

int print()

{

std::cout << " " << shi_bu << " " << xv_bu << std::endl;

return 0;

}

};

shi_shu::shi_shu()

{

}

shi_shu::shi_shu(int i,int j)

{

shi_bu = i;

xv_bu = j;

}

shi_shu::~shi_shu()

{

}

int main()

{

? ? std::cout << "Hello World!\n";

shi_shu A(1,2),B;

A.print();

B = A.add_one();//將A對(duì)象中的值++后拷貝給B對(duì)象

B.print();

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容