课后作业(C++)——day4

1.思维导图

 2.整理类中特殊成员函数:构造函数、析构函数、拷贝构造函数、拷贝赋值函数的使用和实现。

#include <iostream>

using namespace std;
class Stu
{
    string name;
    int age;
    float score;
public:

    //无参构造
    Stu()
    {
        cout << "无参构造" << endl;
    }

    //析构
    ~Stu()
    {
        cout << "析构函数" <<endl;
    }

    //有参构造
    Stu(string name,int age,float score){
        this->name=name;
        this->age=age;
        this->score=score;
        cout << "有参构造" << endl;
    }

    //拷贝构造
    Stu(Stu &ptr)
    {
        this->name=ptr.name;
        this->age=ptr.age;
        this->score=ptr.score;
        cout << "拷贝构造" << endl;
    }
    //拷贝赋值
    Stu &operator=(const Stu &ptr)
    {
        this->name=ptr.name;
        this->age=ptr.age;
        this->score=ptr.score;
        cout << "拷贝赋值" << endl;
    }

    void show()
    {
        cout << name << endl;
        cout << age << endl;
        cout << score << endl;
    }
};

int main()
{
    //无参构造
    Stu s;

    //有参构造
    Stu s1("zhangsan",18,90.5);
    s1.show();

    //拷贝构造函数
    Stu s2=s1;
    s2.show();

    //赋值拷贝
    s=s1;
    s1.show();

    return 0;
}

3.算数运算符重载及赋值运算符重载

#include <iostream>

using namespace std;
class Complex{
    int a;
    int b;
public:
    ~Complex()
    {
        cout << "析构" << endl;
    }
    Complex()
    {
        cout << "无参构造" <<endl;
    }
    Complex(int a,int b)
    {
        this->a=a;
        this->b=b;
        cout << "有参构造" <<endl;
    }
    Complex operator+(Complex &ptr)
    {
        Complex c;
        c.a=this->a+ptr.a;
        c.b=this->b+ptr.b;
        return c;
    }
    void show()
    {
        cout << a <<"+"<< b<< endl;
    }

};
int main()
{
    Complex c1(3,4);
    Complex c2(5,6);
    Complex c3=c1+c2;
    c3.show();
    return 0;
}
#include <iostream>

using namespace std;
class Complex{
    int a;
    int b;
public:
    ~Complex()
    {
        cout << "析构" << endl;
    }
    Complex()
    {
        cout << "无参构造" <<endl;
    }
    Complex(int a,int b)
    {
        this->a=a;
        this->b=b;
        cout << "有参构造" <<endl;
    }
    friend Complex &operator+=(Complex &ptr,Complex &ptr1);
    void show()
    {
        cout << a <<"+"<< b<< endl;
    }

};
Complex &operator+=(Complex &ptr,Complex &ptr1)
{
    ptr.a+=ptr1.a;
    ptr.b+=ptr1.b;
    return ptr;
}
int main()
{
    Complex c1(3,4);
    Complex c2(5,6);
    operator+=(c1,c2);
    c1.show();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值