金 融 学 院 School of Finance
#include iostream.h class Box { private:
int height,width,depth; public:
Box(int ht=2,int wd=3,int dp=4) {
height=ht; width=wd; depth=dp; } ~Box(); int volume() {
return height*width*depth; } };
int main() {
Box thisbox(3,4,5); //初始化 Box defaulbox; //使用默认参数 cout< cout< return 0;
金 融 学 院 School of Finance
}
2.默认构造函数
没有参数或者参数都是默认值的构造函数称为默认构造函数。如果你不提供构造函数,编译器会自动产生一个公共的默认构造函数,这个构造函数什么都不做。如果至少提供一个构造函数,则编译器就不会产生默认构造函数。 3.重载构造函数
一个类中可以有多个构造函数。这些构造函数必须具有不同的参数表。在一个类中需要接受不同初始化值时,就需要编写多个构造函数,但有时候只需要一个不带初始值的空的Box对象。 #include iostream.h class Box { private:
int height,width,depth; public:
Box() { //nothing }
Box(int ht=2,int wd=3,int dp=4) {
height=ht; width=wd; depth=dp; } ~Box(); int volume() {
金 融 学 院 School of Finance
return height*width*depth; } };
int main() {
Box thisbox(3,4,5); //初始化 Box otherbox; otherbox=thisbox; cout< return 0; }
这两个构造函数一个没有初始化值,一个有。当没有初始化值时,程序使用默认值,即2,3,4。
但是这样的程序是不好的。它允许使用初始化过的和没有初始化过的Box对象,但它没有考虑当thisbox给otherbox赋值失败后,volume()该返回什么。较好的方法是,没有参数表的构造函数也把默认值赋值给对象。 class Box {
int height,width,depth; public: Box() {
height=0;width=0;depth=0; }
Box(int ht,int wd,int dp) {
金 融 学 院 School of Finance
height=ht;width=wd;depth=dp; }
int volume() {
return height*width*depth; } };
这还不是最好的方法,更好的方法是使用默认参数,根本不需要不带参数的构造函数。 class Box {
int height,width,depth; public:
Box(int ht=0,int wd=0,int dp=0) {
height=ht;width=wd;depth=dp; }
int volume() {
return height*width*depth; } };
三、析构函数
相关推荐: