class point { private: int xPos; int yPos; public: point(); }; point::point() { xPos = 0; yPos = 0; }
//point.h #include <iostream> using namespace std; class point //point類定義,在定義同時實現其成員函數 { private: //私有成員,分別表明x軸和y軸座標 int xPos; int yPos; public: point(int x, int y) //有參構造函數 { cout << "對象建立時構造函數被自動調用" << endl; xPos = x; yPos = y; } void print() //輸出信息 { cout << "xPos: " << xPos << ",yPos: " << yPos << endl; } }; #include "point.h" int main() { // point pt0;//錯誤的調用,由於咱們已經顯示的定義了一個帶參數的構造函數 // pt0.print();//輸出pt0的信息 point pt1(3, 4); //調用有參構造函數聲明point類變量(類對象)pt1 pt1.print(); //輸出pt1的信息 return 0; }
例1:ios
#include <iostream> using namespace std; class Point { public: Point()//構造函數可以進行重載 { cout << "Point()" << endl; } Point(int ix, int iy) { cout << "Point(int,int)" << endl; _ix = ix; _iy = iy; } void print() { cout << "(" << _ix<< "," << _iy<< ")" << endl; } private: int _ix; int _iy; }; int main(void) { Point p1;//調用默認構造函數 p1.print(); Point p2(3, 4); p2.print(); return 0; }
//point1.h #include <iostream> using namespace std; class point //point類定義,在定義同時實現其成員函數 { public: point(int x, int y)//有參構造函數 { cout << "有參構造函數的調用" << endl; xPos = x; yPos = y; } point() //無參構造函數 { cout << "無參構造函數的調用" << endl; xPos = 0; yPos = 0; } void print()//輸出信息 { cout << "xPos: " << xPos << ",yPos: " << yPos << endl; } private: //私有成員,分泌誒表明x軸和y軸座標 int xPos; int yPos; }; #include "point1.h" int main() { point pt1(3, 4); //調用有參構造函數聲明point類變量(類對象)pt1 pt1.print(); //輸出pt1的信息 point pt2; //調用無參構造函數聲明point類變量(類對象)pt2 pt2.print(); //輸出pt2的信息 return 0; }
point(int x=0,int y=0) { cout<<"對象建立時構造函數被自動調用"<<endl; xPos=x; yPos=y; }
point pt; //x和y都採用默認值0 point pt(3); //x爲3,y採用默認值0 point pt(3,4);//x爲3,y爲4,兩個參數都不採用默認值
point(int x,int y)
{
cout<<"有參構造函數的調用"<<endl;
xPos=x;
yPos=y;
}
//等價於:
point(int x,int y)
:xPos(x)
,yPos(y)
{
cout<<"有參構造函數的調用"<<endl;
}
//point.h #include <iostream> using namespace std; class point { private: int yPos; //先定義 int xPos; //後定義 public: point(int x) :xPos(x) , yPos(xPos) //初始化表取決於成員聲明的順序 //若是換成 //:yPos(y) //,x(yPos)//這樣的話,x先初始化,可是這時yPos尚未初始化,x就是不肯定的值了 { } void print() { cout << "xPos: " << xPos << ", yPos: " << yPos << endl; } }; #include "point.h" int main() { point pt1(3); //調用有參構造函數聲明變量pt1 pt1.print(); return 0; }
#include <iostream> using namespace std; class Point { public: #if 0 Point()//構造函數可以進行重載 { cout << "Point()" << endl; } #endif Point(int ix, int iy) : _ix(ix)//初始化列表 , _iy(iy) { cout << "Point(int,int)" << endl; //_ix = ix;//賦值 //_iy = iy; } void print() { cout << "(" << _ix << "," << _iy << ")" << endl; } private: int _ix; int _iy; }; int main(void) { Point p1;//調用默認構造函數 p1.print(); Point p3(5); p3.print(); Point p2(3, 4); p2.print(); return 0; }