c++:第一课

c++头文件格式:

在这里插入图片描述

#include<fstream> --------->文件头文件
#include<algorithm>----------->算法头文件

#include<iostream>

using namespace std;//namespace是命名空间,std中包含封装好的函数,例如cout
//假如不写namespace std,在使用cout时,格式变更为std::cout;
//自己在规定namespace时,使用的时候,尽量将函数写在namespace的大空间,也就是大括号内。

class inta{
	public://公开区,需要权限最小,都可以访问
		int a;
		void setB(int bb){b=bb;}
		int getB(void){return b;}
		void setC(int cc){c=cc;}
		int getC(void){return c;}
	protected://保护区,允许inta的子类进行访问,外部函数不准访问
		int b;
	private://私有区,只允许自己访问
		int c;	
};
int main(){
	inta r;
	r.a=10;
	r.b=setB(20);
	r.c=setC(30);
	cout<<r.a<<endl<<getB<<endl<<getC<<endl;
}
构造函数
void setB(int bb){b=bb;}
		int getB(void){return b;}
		void setC(int cc){c=cc;}
		int getC(void){return c;}
析构函数
## 暂时不懂
函数重载
//定义三个函数名一样的函数,参数不同
//主函数在引用函数时,是根据参数的不同自主判断该引用的函数
#include <iostream>
	#include <fstream>
	
	using namespace std;
	void fun(int t)
	{
		cout << "t = " << t << endl;
		cout << "int" << endl;
	}
	void fun(int ,double){
	cout << "int double" << endl;	
	}
	#include <string>
	void fun(string){
	cout << "string" << endl;
	}
	void fun(double d){
	cout << "double"<< endl;
	}
	int main(){
		fun(1,2.3);
		fun("NBA");	
		fun(3.4);
	return 0;
	}

C++支持函数重载,C不支持(也就是所谓的函数名一样)

引用
#include<stdio.h>
#include<stdlib.h>
void turn(int &x, int &y)//有引用,交换值有效(即引用就是函数的别名)
{
        int t;
        t = x;
        x = y;
        y = t;
}
int main()
{
    int a, b;
    scanf_s("%d%d", &a, &b);
    turn(a, b);
    printf("%d %d\n",a,b);
    system("pause");
    return 0;
}

https://blog.csdn.net/dujiangyan101/article/details/2844138
指针和引用的异同详见上方链接
在使用函数的时候,参数直接写,不用更改

运算符重载
#include<iostream>
#include<algorithm>
using namespace std;
namespace arc{//定义一个arc的命名空间
struct rect{
	public:
	rect(int w=1,int l=1){
		width=w;
		len=l;
	}
	double area(void){
		return width*len;
	}
	double lenth();
	private:
		double width;
		double len;
 };

double rect::lenth(){
	return 2*(width+len);
}

bool operator<(rect r,rect l){//运算符重载,格式《(函数类型) operator (要重载的)(参数)》
	return r.area()<l.area();
}
bool operator>(rect r,rect l){
	return r.lenth()>r.lenth();
}
}
int main(){
	using namespace arc;
	rect r[5]={rect(10,100),rect(10,20),rect(200,20),rect(30,40),rect(30,50)};
	
//	cout <<"area="<<r.area()<<endl;
//	cout <<"lenth="<<r.lenth()<<endl	
//	
	sort(r,r+5);
	cout<<"sort=";
	for(int i=0;i<5;i++) cout<<r[i].area()<<endl;
	sort(r,r+5,std::greater<rect>());
	cout<<"lenth=";
	for(int i=0;i<5;i++) cout<<r[i].lenth()<<endl;
	return 0;	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值