一个程序弄懂C++面向对象编程

没有继承和友元函数的内容,而且太乱了,以后可能会修改,但对我来说够用了

//huaruoji on 2021/2/1
#include <bits/stdc++.h>

using namespace std;

struct test
{
	//struct中的成员均为public成员 
	static int pi,e;//声明了pi和e,但此处只是声明,不能接着赋值 
	int a,b,c;//实例变量 
	test(int p,int q)//构造函数定义 
	{
		a=p,b=q;
	}
	test(char s)//构造函数定义 
	{
		c=s-'A';
	}
	
	/*
	下面这个函数的返回值为bool,重载的运算符为<,运算符左边的数据类型为test,右边
	的数据类型也为test
	括号内const和&的用途在于加速和不改变源值
	第二个const放在非静态成员函数的尾部,表示该非静态成员函数不修改对象内容
	*/
	bool operator < (const test &m) const
	{
		if(a<m.a) return false;
		else return true;
	}
	bool operator > (const test &m) const
	{
		if(b>m.b) return true;
		else return false;
	}
	int operator + (const test &m) const 
	{
		return a+b+m.a+m.b;
	}
	test operator - (const test &m) const
	{
		test q(a-m.a,b-m.b);
		return q;
	}
	
	//声明成员函数 
	bool isab(void) const;//const可加可不加 
	int *address(void); //但这里const不能加,因为返回的是地址 
	//定义成员函数 
	bool compare(int com) 
	{
		return (com<a);
	}	
	
	int compare2(test rec)
	{
		return (this->compare(5)<rec.compare(1));//this指针的用法 
	}
};

//定义test中的成员函数 
bool test::isab() const
{
	return (a==b);
}
int *test::address()//一个返回地址的函数 
{
	return &a; 
}


int test::pi;//定义了pi
int test::e=2;//定义并初始化了e 

int main()
{
	test::pi=1;//初始化了pi 
	
	test a=test(3,5);//main函数中的局部对象 
	test b(3,5);
	test c('A');
	test d(4,6);
	cout<<a.a<<' '<<b.b<<' '<<c.c<<' '<<a.isab()<<endl;
	
	cout<<(a<b)<<' '<<(a>b)<<' '<<(a+b)<<' '<<(b-d+a)<<endl;
	
	int m=*b.address();
	cout<<m<<endl;
	cout<<a.compare(1)<<endl;
	cout<<a.compare2(b);
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值