C++知识点案例 笔记-1

1.重载函数
2.内联函数
3.New、Delete
4.重载与、const形参
5.常数据成员
6.静态成员函数

==重载函数==
#include <iostream>
using namespace std;
void add(int x,int y)
{
    cout<<x + y<<endl;
}
void add(float x)
{
    cout<<x + 10<<endl;
}
double add(double x,double y)
{
    return x + y;
}
int main()
{
    add(1,6);
    add(3.89);
    cout<<add(1.2,1.6)<<endl;//函数名相同自动按传入的参数区分运行相应函数

	return 0;
}

==内联函数==
#include <iostream>
//#include <string>
using namespace std;
inline void love(int i)
{
    cout<<"我喜欢你"<<i<<"天了"<<endl;
}
int main()
{
    for(int k=0;k<100000;k++)
        love(k);          //相当于函数在此镶嵌写入,比调用运行更快

	return 0;
}

==New、Delete==
#include <iostream>
#include <string>
using namespace std;
int main()
{
    int *pi= new int(10);
    cout<<"*pi:"<<*pi<<endl;
    *pi=20;
    cout<<"*pi:"<<*pi<<endl;
    char *pc= new char[10];
    for(int i=0;i<10;i++)
        pc[i]=i+65;
    for(int k=0;k<10;k++)
        cout<<pc[k]<<endl;
    delete pi;
    delete []pc;
	return 0;
}

==重载与、const形参==
#include <iostream>
using namespace std;
void func1(const int *x)
{
    cout<<"常量指针:"<<*x<<endl;
}
void func1(int *x)
{
    cout<<"普通指针:"<<*x<<endl;

}
void func2(const int&x)
{
    cout<<"常量引用:"<<x<<endl;
}
void func2(int&x)
{
    cout<<"普通引用:"<<x<<endl;
}
int main()
{
    const int c=1;
    int d=2;
    func1(&c);//常量参数
    func1(&d);//非~
    
    func2(c);//常量参数
    func2(d);//非~
    return 0;
}

==常数据成员==
#include <iostream>
using namespace std;
class circle
{
public:
    circle(double r);
    double c_c();
private:
    double R;
    const double pai;
};
circle::circle(double r):pai(3.1415926)
{
    R = r;
}
double circle::c_c()
{
    return 2*pai*R ;
}
int main()
{
    cout<<"请输入半径:"<<endl;
    double pk;
    cin>>pk;
    circle q_c(pk);
    cout<<"计算得周长为:"<<q_c.c_c()<<endl;
    //system("pause");
    return 0;
}


==静态成员函数==

#include <iostream>
#include <string>
using namespace std;
class student
{
public:
    student (string name,int id);
    string get_name();
    static int get_total();
    static int get_total(student&stdref);
private:
   static int Total;
   string Name;
   int Id;

};
student::student(string name,int id):Name(name)
{
    Total++;
    Id = id;
}
string student::get_name()
{
    return Name;
}
int student::get_total(student&stdref)
{
    cout<<stdref.Name<<"被清华录取了"<<endl;
    return Total;
}
int student::get_total()
{
    return Total;
}
int student::Total = 0;
int main()
{
    cout<<"原来总人数"<<student::get_total()<<endl;
    student std_tom("tom",12580);
    cout<<"姓名:"<<std_tom.get_name()<<"
变化后的总人数:"<<std_tom.get_total(std_tom)<<endl;
    //通过访问对象访问静态成员函数
    return 0;

}



________________________________________________________

Every good deed you do will someday come back to you.

Love you,love word !
原文地址:https://www.cnblogs.com/hugboy/p/12728028.html