4.1作业

本文详细讲解了在C++中菱形继承结构下的类(如A、B、C、D)的构造函数(有参和无参)、析构函数、拷贝构造函数和拷贝赋值函数的实现,以及如何在主函数中操作这些对象。
摘要由CSDN通过智能技术生成
  1. 对菱形继承给出的代码中每一个类,写一个有参构造函数
  2. 写出下列类的,构造函数(有参、无参),析构函数,拷贝构造函数和拷贝赋值函数

class Father { int *p; const string name; } class Son:public Father { int *age;

     3整理思维导图

#include <iostream>
using namespace std;

class A {
public:
    int a;
    A(int value) : a(value) {} // 添加有参构造函数
};

class B : virtual public A {
public:
    int b;
    B(int valueA, int valueB) : A(valueA), b(valueB) {} 
};

class C : virtual public A {
public:
    int c;
    C(int valueA, int valueC) : A(valueA), c(valueC) {} 
};

// 汇集子类
class D : public B, public C {
public:
    int d;
    D(int valueA, int valueB, int valueC, int valueD)
        : A(valueA), B(valueA, valueB), C(valueA, valueC), d(valueD) {}
};

int main() {
    
    D d1(90, 100, 110, 120); 

    d1.a = 90;
    d1.B::a = 80;
    d1.C::a = 80;

    return 0;
}

#include <iostream>
#include <string>
using namespace std;

class Father
{
    int *p;
    const string name;

public:
    
    Father() : p(new int), name("Default Father") {
        cout << "Father无参构造函数" << endl;
    }

   
    Father(int value, const string& father_name) : p(new int(value)), name(father_name) {
        cout << "Father有参构造函数" << endl;
    }

  
    Father(const Father& other) : p(new int(*other.p)), name(other.name) {
        cout << "Father拷贝构造函数" << endl;
    }

   
    Father& operator=(const Father& other) {
    
        cout << "Father拷贝赋值函数" << endl;
        return *this;
    }

   
    ~Father() {
        cout << "Father析构函数,准备释放空间:" << p << endl;
        delete p;
    }
};

class Son : public Father
{
    int *age;

public:
    
    Son() : Father(), age(new int) {
        cout << "Son无参构造函数" << endl;
    }

   
    Son(int father_value, const string& father_name, int son_age)
        : Father(father_value, father_name), age(new int(son_age)) {
        cout << "Son有参构造函数" << endl;
    }

   
    Son(const Son& other) : Father(other), age(new int(*other.age)) {
        cout << "Son拷贝构造函数" << endl;
    }

    
    Son& operator=(const Son& other) {
       
        cout << "Son拷贝赋值函数" << endl;
        return *this;
    }
   
    ~Son() {
        cout << "Son析构函数,准备释放空间:" << age << endl;
        delete age;
    }
};

int main()
{
    Son s1(10, "Father1", 23);
    Son s2 = s1;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值