public:
voidplay ();//声明函数private:
string name;
int age;
};
void people :: play(){ //::意为play为people类中的函数
count<<"i am so happy !"<<endl;
};
内置函数inline
对于内置函数的处理,是将程序嵌入到调用点,并非正常的调用,所以执行效率很高。
由于调用函数的效率一般较低,而对于规模较小的函数一般采用内置的方式。
class people {
inline void eat();
void play (){//类中的函数默认为内置函数,不用声明。
...
}
};
inline void people::eat(){//类外函数如果是内置函数要声明。
...
}
对象实例化
classdog{
string name;
int age;
};
dog xiaoha = {
"hashiqi",3};//实例化一只哈士奇
构造函数
构造函数自动执行且执行一次。
#include <iostream>usingnamespacestd;
class Time {
public:
Time(){ //构造成员函数
hour=0;
minute=0;
sec=0;
}
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
void Time::set_time(){
cin>>hour>>minute>>sec;
};
void Time::show_time(){
cout<<hour<<minute<<sec;
};
int main() {
Time t1;
t1.set_time();
t1.show_time();
return0;
}
带参构造函数
#include <iostream>usingnamespacestd;
class Box{
//类名首字母最好大写public:
Box(int,int,int);//声明带参数的构造函数int volume ();//声明计算体积的函数private:
int height;
int width;
int length;
};
//实现构造函数以及成员函数
Box::Box(int h,int w,int l){
height = h;
width = w;
length = l;
}
int Box::volume(){
cout<< height*width*length;
}
int main() {
Box b1(12,13,14);
b1.volume();
return0;
}
参数初始化列表对成员进行初始化
class People{
public:
People(int nu,int s,int na):num(s),sex(s),{strcpy(name,na);}
//通过:后面的列表将对应的属性初始化;private:
int num;
char sex;
char name[20];
};
//实例化对象如下
People p1(01,'F',"Eric");
构造方法的重载
#include <iostream>usingnamespacestd;
class Box{
//类名首字母最好大写public:
Box ();
Box(int h,int w,int l):height(h),width(w),length(l){}//构造函数的重载int volume ();//声明计算体积的函数private:
int height;
int width;
int length;
};
int Box::volume(){
cout<< height*width*length;
}
int main() {
Box b1(12,13,15);
b1.volume();
return0;
}
析构函数
是希望对象最后一次执行所要做的事
#include <iostream>usingnamespacestd;
class Box{
//类名首字母最好大写public:
Box ();
Box(int h,int w,int l):height(h),width(w),length(l){}//构造函数的重载
~Box(){ //析构函数cout<<'\n'<<"啊。我马上要死了,析构函数要杀了我。";
}
int volume ();//声明计算体积的函数private:
int height;
int width;
int length;
};
int Box::volume(){
cout<< height*width*length;
}
int main() {
Box b1(12,13