带参数的构造函数
#include<iostream>
using namespace std;
class Point {
//成员变量x, y
int x, y;
public:
//带两个参数的构造函数
Point(int a = 8, int b = 8) {
x = a;
y = b;
cout<<"我是构造函数,请用我啦!"<<endl;
}
void show() {
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main () {
Point p1;
p1.show();
Point p2(5, 6);
p2.show();
Point p3(1);
p3.show();
return 0;
}
执行结果:
可以输入数据的构造函数
#include<iostream>
using namespace std;
class Point {
//成员变量x, y
int x, y;
public:
//不带参数的构造函数
Point() {
cout<<"Input x and y"<<endl;
cin>>x>>y;
cout<<"我是可以输入数据的构造函数"<<endl;
}
/*
//带两个参数的构造函数
Point(int a = 8, int b = 8) {
x = a;
y = b;
cout<<"我是构造函数,请用我啦!"<<endl;
}
*/
void show() {
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main () {
Point p1;
p1.show();
/*
Point p2(5, 6);
p2.show();
Point p3(1);
p3.show();
*/
return 0;
}
执行结果:
小结:这两种函数不能同时存在,否则,对象不知道调用哪一个,即产生了歧义
错误示例:
#include<iostream>
using namespace std;
class Point {
//成员变量x, y
int x, y;
public:
//不带参数的构造函数
Point() {
cout<<"Input x and y"<<endl;
cin>>x>>y;
cout<<"我是可以输入数据的构造函数"<<endl;
}
//带两个参数的构造函数
Point(int a = 8, int b = 8) {
x = a;
y = b;
cout<<"我是构造函数,请用我啦!"<<endl;
}
void show() {
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main () {
Point p1;
p1.show();
/*
Point p2(5, 6);
p2.show();
Point p3(1);
p3.show();
*/
return 0;
}