无参有参构造函数
無參構造函數
class Location_1 { public:Location_1(){cout << "調用無參構造函數" << endl;}private:int x;int y;};void main() {// 調用的就是無參構造函數// 這個無參構造函數不寫也是有默認的Location_1 l1;system("pause");return; }下面的這種無參函數的調用方式是錯誤的:
void main() {Location_1 l1(); // 注意這個調用是錯誤的cout << "x : " << l1.getX() << ", y : " << l1.getY() << endl; // 并且這段代碼還是會報錯的system("pause");return; }或者你直接手動調用無參構造函數
Location_1 l1 = Location_1();有參構造函數調用的三種方法
括號法 等號法 手動調用:
class Location_1 { public:Location_1(){cout << "調用無參構造函數" << endl;}Location_1(int x){this->x = x;this->y = 0;}Location_1(int x, int y){this->x = x;this->y = y;}public:void setX(int x){this->x = x;}int getX(){return this->x;}void setY(int y){this->y = y;}int getY(){return this->y;}private:int x;int y;};void main() {// Location_1 l1(1); // 調用一個參數的構造函數 (括號法)// Location_1 l1 = (1); // C++調用有參構造函數 (等號法)// Location_1 l1(1, 2); // 調用兩個參數的構造函數 (括號法)// Location_1 l1 = (1, 2); // (等號法)Location_1 l1 = Location_1(1, 2); // 手動調用構造函數的方法cout << "x : " << l1.getX() << ", y : " << l1.getY() << endl;system("pause");return;}總結
- 上一篇: JavaScript代码在哪里放置?
- 下一篇: java无参_Java——类的无参、带参