• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LOFLY
终其一生,编织快乐
博客园    首页    新随笔    联系   管理    订阅  订阅

C++之链式调用

C++之链式调用

C++之链式调用

先不考虑函数返回值为引用的情况
代码如下:

#include <iostream>
using namespace std; 

// this可以解决命名冲突
class Person{

public :
	Person(int age){
		this->age = age;
	}
	
	Person(const Person &p){
	    this->age = p.age;
	}
	
	int age;
	void compareAge(Person &p)
	{
		if (this->age == p.age ){
			cout << "Age is equal" << endl;
		}
		else cout << "Age is unequal" << endl;
	}
	Person  addAge(Person &p ){
		this -> age  +=  p.age;
		return *this; // *this 指向本体
	}
	
	
};

void  test01()
{
	Person p1(10);
	Person p2(110);
	cout << p1.age << endl;
	p1.compareAge(p2);
	
// 	p1.addAge(p2).addAge(p2).addAge(p2); // 链式编程
    Person p =  p1.addAge(p2).addAge(p2).addAge(p2);
    
    
	cout << p1.age << endl;
	cout << p.age <<endl;
}

int main()
{
	test01();
	system("pause"); 
	return EXIT_SUCCESS; 
}

运行结果:

10
Age is unequal
120
340

代码第24行的addAge方法的返回值返回的时Person对象,函数返回时会调用Person的拷贝构造函数,所以时一个新对象。
看下面的代码:

#include <iostream>
using namespace std; 

// this可以解决命名冲突
class Person{

public :
	Person(int age){
		this->age = age;
	}
	
	Person(const Person &p){
	    this->age = p.age;
	}
	
	int age;
	void compareAge(Person &p)
	{
		if (this->age == p.age ){
			cout << "Age is equal" << endl;
		}
		else cout << "Age is unequal" << endl;
	}
	Person & addAge(Person &p ){
		this -> age  +=  p.age;
		return *this; // *this 指向本体
	}

};

void  test01()
{
	Person p1(10);
	Person p2(110);
	cout << p1.age << endl;
	p1.compareAge(p2);
	
// 	p1.addAge(p2).addAge(p2).addAge(p2); // 链式编程
    Person p =  p1.addAge(p2).addAge(p2).addAge(p2);
    
    
	cout << p1.age << endl;
	cout << p.age <<endl; 
}

int main()
{
	test01();
	system("pause"); 
	return EXIT_SUCCESS; 
}

运行结果:

10
Age is unequal
340
340

上面代码第24行,方法的返回值是引用。

补充:
看下面代码:

#include <iostream>
using namespace std; 

class Person{
public :
	void show(){
		cout << "Person show" << endl;
	}
	void showAge(){
		cout <<m_Age << endl;
	}
	int m_Age;
};

void test01()
{
	Person *p = NULL;
	p ->show (); // 这句代码可以运行成功
	/*p ->showAge();*/ //  涉及访问类的成员变量,而指针指向的是NULL , 无法访问成员变量
}

int main()
{
	test01();
	system("pause"); 
	return EXIT_SUCCESS; 
}

C++成员函数是放在公共区域的,对象只保存对象成员属性。

posted @ 2022-08-14 08:14  编织快乐  阅读(624)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3