16.1.25
一、对象的动态建立和释放
使用new和delete,动态分配和撤销内存。
例如:new box
在此空间中存放一个box类对象,同时调用该类的构造函数,以使该对象初始化。但用户无法访问因为此对象无对象名,用户也不知道地址。
Box *pt;
Pt=new box;\\在pt中存放新建对象的起始地址
二、对象的赋值和复制
①对象的赋值
Student stud1,stud2;
Stud2=stud1;
②对象的复制
类名对象2(对象1),用对象1复制出对象2
类名对象名1=对象名2,对象2复制对象1.
三、静态成员
如果希望各对象中的数据成员的值是一样的,就可以定义为静态数据成员。
Class box
{public:
Intvolume();
Private:
Staticint height;
Intwidth;
Intlength;
};
Int box::height=10;
静态成员可以初始化,但只能类体外进行初始化。不能用初始化表对数据进行初始化!!
静态成员函数
Static intvolume();
静态成员函数是类的一部分而不是对象的一部分。如果要在类外调用公用的静态成员函数,要用类名和域运算符“:”。
Box::volume()
静态成员函数没有this指针,所以不能访问非静态成员
using namespacestd;
class time
{public:
time(int,int,int);
friend void display(time&);
private:
inthour;
intminute;
intsec;
};
time::time(inth,int m,int s){
hour=h;
minute=m;
sec=s;
}
voiddisplay(time&t)
{cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
}
int main(){
time tl(10,13,56);
display(tl);
return 0;
}
四、类模板
对于类的声明来说,其功能是相同的,仅仅是数据类型不同。
声明Template <classnumtype>
定义:类模板名<实际类型名> 对象名(参数表)
如:compare<int>cml(4,6)
例子:
using namespacestd;
template<classnumtype>
class compare
{public:
compare(numtype a,numtype b);
numtype max();
numtype min();
private:
numtype x,y;
};
template<classnumtype>
compare<numtype>::compare(numtypea,numtype b){
x=a;
y=b;
}
template<classnumtype>
numtypecompare<numtype>::max(){
return(x>y)?x:y;
}
template<classnumtype>
numtypecompare<numtype>::min(){
return(x<y)?x:y;
}
int main(){
compare<int> cmpl(3,7);
cout<<cmpl.max()<<endl;
}