• 一个程序弄懂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;
    }
    
  • 相关阅读:
    有赞移动Crash平台建设
    软件测试创新之路
    手把手教你用Python实现智能推荐算法
    接口测试--参数实现MD5加密签名规则
    重置一发LCT模板
    LOJ #2131. 「NOI2015」寿司晚宴
    LOJ #3119「CTS2019 | CTSC2019」随机立方体 (容斥)
    2019牛客暑期多校训练营(第九场)
    20190815模拟赛
    zhengrui集训笔记2
  • 原文地址:https://www.cnblogs.com/huaruoji/p/14425571.html
Copyright © 2020-2023  润新知