欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

无参有参构造函数

发布时间:2023/12/14 编程问答 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 无参有参构造函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
无参构造函数
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;}

总结

以上是生活随笔为你收集整理的无参有参构造函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。