C++ this指针初步使用,与链式编程
生活随笔
收集整理的這篇文章主要介紹了
C++ this指针初步使用,与链式编程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;class Person {
public:int m_age;Person(int age) {this->m_age = age;}Person & addAge(Person &p) { // 返回對象的引用this->m_age += p.m_age;return *this; // 返回對象本體}void showAge() {cout << this->m_age << endl;}
};void test1() {Person p1(18);Person p2(10);p1.addAge(p2).addAge(p2).addAge(p2); // 鏈式編程p1.showAge();
}int main()
{test1();return 0;
}
this指針的本質是一個指針常量,type * const this,
即this指向的值可以改, 但this的指向(即this的值)不可以改, 如果想讓this指向的值也不可以改,再加上 一個 const type * const this; 就可以了.
注意這里 Person & addAge(Person &p) 返回的是一個對象的引用
即this指向的值可以改, 但this的指向(即this的值)不可以改, 如果想讓this指向的值也不可以改,再加上 一個 const type * const this; 就可以了.
總結
以上是生活随笔為你收集整理的C++ this指针初步使用,与链式编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 有参构造 无参构造 拷贝构造 以
- 下一篇: C++ 常函数 常对象 初步