构造函数有参数,无参数,重载的运用

本文详细介绍了无参数构造函数的概念及使用方式,并通过具体的C++代码示例展示了构造函数的定义与重载技巧。
作者:范星月

无参数的构造函数:

#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="" />
学习总结:构造函数很重要,类中必须有合适的构造函数



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值