作者:范星月
无参数的构造函数:
#include <iostream>
#include<cstdio>
using namespace std;
class Rectangle
{
private:
double x1,x2,y1,y2;
public:
Rectangle();
void input();
void output();
};
Rectangle::Rectangle()
{
double a,b,c,d;
x1=a;
x2=b;
y1=c;
y2=d;
}
void Rectangle::input()
{
cin>>x1>>x2>>y1>>y2;
}
void Rectangle::output()
{
cout<<(x1-x2)*(y1-y2);
cout<<endl;
}
int main()
{
Rectangle p1;
p1.input();
p1.output();
return 0;
}
//无参数的构造函数
#include <iostream>
#include<cstdio>
using namespace std;
class Rectangle
{
private:
double x1,x2,y1,y2;
public:
Rectangle(){}//有没有均可以,或者是Rectangle();
Rectangle(double a,double b,double c,double d):x1(a),x2(b),y1(c),y2(d) {}
void output();
};
void Rectangle::output()
{
cout<<(x1-x2)*(y1-y2);
cout<<endl;
}
int main()
{
Rectangle p1(1,3,5,7);
p1.output();
return 0;
}
//构造函数重载时应该注意的地方
#include <iostream>
#include<cstdio>
using namespace std;
class Rectangle
{
private:
double x1,x2,y1,y2;
public:
Rectangle(){}//在构造函数重载时,没有大括号不行
Rectangle(double a,double b,double c,double d):x1(a),x2(b),y1(c),y2(d) {}
void input();
void output();
};
void Rectangle::input()
{
cin>>x1>>x2>>y1>>y2;
}
void Rectangle::output()
{
cout<<(x1-x2)*(y1-y2);
cout<<endl;
}
int main()
{
Rectangle p1(1,3,5,7);
p1.output();
Rectangle p2;
p2.input();
p2.output();
return 0;
}
<img src="https://img-blog.youkuaiyun.com/20150505174312033?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTcxNjEyMQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
学习总结:构造函数很重要,类中必须有合适的构造函数