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;
}

注意这里 Person & addAge(Person &p) 返回的是一个对象的引用

  1. this指针的本质是一个指针常量,type * const this,
    即this指向的值可以改, 但this的指向(即this的值)不可以改, 如果想让this指向的值也不可以改,再加上 一个 const type * const this; 就可以了.
发布了100 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43903378/article/details/103841193