- 对菱形继承给出的代码中每一个类,写一个有参构造函数
#include <iostream> using namespace std; class A { public: int a; A(int a):a(a){} }; class B:virtual public A { public: int b; B(int b,int a):b(b),A(a){} }; class C:virtual public A { public: int c; C(int a,int c):c(c),A(a){} }; //汇集子类 class D:public B,public C { public: int d; void show() { cout << B::a << endl; } D(int a,int b,int c,int d):B(b,a),C(a,c),A(a),d(d){} }; int main() { //实例化汇集子类D的类对象 D d1(10,23,90,100); d1.a = 90;//对于公共基类继承加上virual后,在汇集子类中只能找到一个属性a d1.B::a = 80; d1.show(); cout << d1.B::A::a<< endl; return 0; }
- 写出下列类的,构造函数(有参、无参),析构函数,拷贝构造函数和拷贝赋值函数
class F { int *p; const string name; } class C:public F { int *age; }
#include <iostream> using namespace std; class F { int *p; const string name; public: F():p(new int),name("张三"){} //让p成员指向堆区的空间 F(int a,string name):p(new int(a)),name(name){cout<<"F有参构造"<<endl;} F(const F &other):p(new int(*(other.p))),name(other.name) { cout<<"F的深度拷贝"<<endl; } ~F() { cout<<"准备释放空间: "<<p<<endl; delete p; cout<<"F的析构"<<endl; } F &operator=(const F &other) { *(this->p) = *(other.p); cout<<"F拷贝赋值"<<endl; return *this; } void show() { cout<<"p的指向:"<<p<<endl; cout<<"*p = "<<*p<<endl; cout<<"name = "<<name<<endl; } }; class C:public F { int *age; public: C():F(),age(new int){} //C的无参构造 C(int age,int a,string name):age(new int(age)),F(a,name) { cout<<"C的有参构造"<<endl; } C(const C &other):age(new int(*(other.age))),F(other) { cout<<"C的深度拷贝"<<endl; } ~C() { cout<<"C的析构"<<endl; } C &operator=(const C &other) { *(this->age)=*(other.age); F::operator=(other); return *this; } }; int main() { C c1(21,90,"历史"); C c2 = c1; cout<<" c2 深度拷贝"<<endl; c2.show(); cout<<" c1 "<<endl; c1.show(); C c3; c3 = c2; cout<<" c2 拷贝赋值"<<endl; c2.show(); cout<<"-----------------------------"<<endl; cout<<" c3 "<<endl; c3.show(); cout<<endl; cout<<"开始析构"<<endl; return 0; }
4.1C++
最新推荐文章于 2024-09-16 17:46:36 发布