- 对菱形继承给出的代码中每一个类,写一个有参构造函数
- 写出下列类的,构造函数(有参、无参),析构函数,拷贝构造函数和拷贝赋值函数
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) {
if (this != &other) {
delete p;
p = new int(*other.p);
name = other.name; // 不需要处理,因为name是const string类型,不可变
}
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) {
if (this != &other) {
Father::operator=(other);
delete age;
age = new int(*other.age);
}
cout << "Son拷贝赋值函数" << endl;
return *this;
}
~Son() {
cout << "Son析构函数,准备释放空间:" << age << endl;
delete age;
}
};
int main()
{
Son s1(10, "Father1", 23);
Son s2 = s1;
return 0;
}