c++头文件格式:
#include<fstream> --------->文件头文件 #include<algorithm>----------->算法头文件
#include
<iostream>
using namespace std
;
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
{
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
){
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)};
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;
}