C++におけるコンストラクション関数の役割
5848 ワード
コンストラクション関数クラス内のオブジェクトの初期化を解決するための問題コンストラクション関数は特殊な関数であり、他のメンバー関数とは異なり、コンストラクション関数はユーザーが呼び出す必要がなく、オブジェクトを構築するときに自動的に実行されます.
コンストラクション関数は、ユーザ呼び出しを必要とせず、ユーザに呼び出されることもできない.
パラメータ付きコンストラクション関数
オブジェクトを定義するときに与えられるパラメータ付きコンストラクション関数のパラメータ.パラメータ付きコンストラクション関数を使用すると、異なるオブジェクトの初期化を容易に実現できます.
#include
//#include "student.h"
//#include
//#include
using namespace std;
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;
cin>>minute;
cin>>sec;
}
void Time::show_time() {
cout<":"<":"<int main() {
Time t1;
t1.set_time();
t1.show_time();
Time t2;
t2.show_time();
return 0;
}
コンストラクション関数は、ユーザ呼び出しを必要とせず、ユーザに呼び出されることもできない.
パラメータ付きコンストラクション関数
#include
//#include "student.h"
//#include
//#include
using namespace std;
class Box{
public:
Box(int,int,int);
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h, int w, int len) {
height=h;
width=w;
length=len;
}
int Box::volume() {
return height*width*length;
}
int main() {
Box box1(12,25,36); // box1
cout<<"the voluime of box1 is"<15,65,32);
cout <<"the volume of box2 is"<return 0;
}
オブジェクトを定義するときに与えられるパラメータ付きコンストラクション関数のパラメータ.パラメータ付きコンストラクション関数を使用すると、異なるオブジェクトの初期化を容易に実現できます.
#include
//#include "student.h"
//#include
//#include
using namespace std;
class Box{
public:
Box();
Box(int h,int w,int len):height(h),width(w),length(len){} //
//// ,
int volume();
private:
int height;
int width;
int length;
};
Box::Box() {
height=5;
width=8;
length=23;
}
int Box::volume() {
return height*width*length;
}
int main() {
Box box1; // box1
cout<<"the voluime of box1 is"<15,65,32);
cout <<"the volume of box2 is"<return 0;
}