总结
1.函数里面调用函数:
int compute(int a,int b,int(*func)(int,int)){
return (*func)(a,b);
}
2.指针和引用
bool s2(const Student &a1, const Student & a2){
if(a1.score[0]+a1.score[1]>a2.score[0]+a2.score[1]) return true;
else if((a1.score[0]+a1.score[1]==a2.score[0]+a2.score[1])&&a1.num<a2.num) return true;
else return false;
}
Student st[](或 Student* st):表明函数接收的是一个数组或者指向数组首元素的指针。函数能够访问数组里的多个元素,这在需要遍历数组元素时是必要的。
Student& st:意味着函数接收的是一个单独的 Student 对象的引用。借助这个引用,函数可以对该对象进行修改,但它只能操作这一个对象,无法访问数组中的其他元素。
int select(Student st[],int n,bool(*func)(const Student &a, const Student &b)){
int max=0;
for(int i=1;i<n;i++){
if(func(st[max],st[i]))continue;
else max=i;
}
return st[max].num;
}
select 函数的用途是在 Student 数组里找出满足特定条件(由 func 函数指定)的学生编号。所以,函数必须能够访问数组中的所有元素,进而进行比较。要是使用 Student& st,函数就只能操作一个 Student 对象,无法实现遍历数组并比较元素的功能。
4.指针类型调用->
5.Student::count中count是静态成员变量
static int count;
int Student::count=0;//类外初始化
涉及静态成员的函数构造前要加static
class Client{
private:
static char ServerName;
static int ClientNum;
public:
Client(){ClientNum++;}
static void show(){
cout<<"server name:"<<ServerName<<endl<<"num of clients:"<<ClientNum<<endl;
}
static void changeServerName(char a){
ServerName=a;
}
};
char Client::ServerName='A';
int Client::ClientNum=0;
6.运算符重载
返回类型 operator 运算符(参数列表) {
// 函数体
}
友元函数形式的运算符重载
friend 返回类型 operator 运算符(参数列表) {
// 函数体
}
比如,重载>>以实现输入
class Student{
private:
string name;
int score;
public:
friend istream& operator>>(istream&is,Student&st){
is>>st.name>>st.score;
return is;
}
static int num;
friend ostream&operator<<(ostream&os,Student&st){
os<<(++Student::num)<<". "<<st.name<<" ";
string grade=st.score>=60?"PASS":"FAIL";
os<<grade;
return os;
}
};int Student::num=0;
istream& 代表对 istream 对象的引用
istream& is:这个参数是输入流对象的引用,一般是 cin,不过也可以是文件输入流等其他输入流。借助这个参数,函数就能从输入流中读取数据。
Student& s:这是要输入数据的 Student 对象的引用。通过引用传递,可以直接修改该对象的成员变量
7.限制输出的小数位数
#include<iomanip>
cout<<fixed<<setprecision(2)<<num<<endl;
8.辗转相除法
最大公约数(gcd)
int gcd(int a,int b){
while(b!=0){
int temp=b;
b=a%b;
a=temp;
}return a;
}
最小公倍数(lcm)
int lcm(int a,int b){
return(a/gcd(a,b))*b;//先除后乘防止溢出
}