通用对象的四大默认函数
1、构造器:类名(形参列表)构造体 如:class Date {
//构造函数(初始化列表)进行类的初始化
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
private:
int year;
int month;
int day;
};
作用:在类创建对象时,自动调用,完成对类对象的初始化
屌屌的初始化:初始化列表——初始化列表中的被初始化顺序与声明顺序有关
2、析构器:~类名()
如:~A()
作用:对象消失的时候自动调用
3、拷贝构造器:类名(形参列表 (如:const 类名 &other))
什么时候用:由已存在的对象创建新对象,新对象不由构造器来构造,而是由拷贝构造器来完成
class Date{
public:
Date (int y=0,int m=0,int d=0);
Date(const Date& another){
year=another.year;
month=another.month;
day=another.day;
}
private:
int year;
int month;
int day;
}
}
main(){
Date d(2008,8,8);
Date D(d);
}
4、运算符重载:返回值类型(类名&) operator 运算符(形参列表(如:const 类名 &---)){重载实体}
返回值类型可以是: 也可以是普通类型
如:类名& operator=(const 类名& another);
main(){
string s1="china";
string s2=s1;//s2.operator(s1)
string s3=s2;//s3.operator(s2.operator(s1))
}
如: bool operator=(const 类名 &another){}
5.友元:破坏封装 但是有利于频繁调用
class A{Public:friend Class B}//B是类A的友元类 可以通过B的对象访问A的私有成员
类外:A operator+(A& one,A& Another)
类内: friend A operator+(A& one,A& Another)