关于actor和继承

about ctors and inheritance

本文关键字:继承 actor 关于      更新时间:2023-10-16

我对c++有点陌生。我有一个分配,我应该实现c类的默认变量和变量,以便它们分别打印"c::变量"answers"c::变量"。我不知道如何处理这件事,希望你能帮助我。

#include <iostream>
#include <string>
using namespace std;
class a {
public:
    a(const char* sname)
        :  _sname(sname) {
        cout << "a::ctor" << endl;
    }
    a(const a& s) { cout << "a::copy ctor" << endl; }
    virtual ~a() { cout << "a::dtor " << endl; }
    void f1() { cout << "a::f1()" << endl; f2(); }
    virtual void f2() = 0;
private:
    string _sname;
};
class b1 : virtual public a {
public:
    b1(const char* saname, const char* ssname)
        : _sname1(saname), a(ssname) {
    }
    b1(const b1& b1) : a(b1) { cout << "b1 :: copy ctor << endl"; }
    ~b1() { cout << "b1::dtor" << endl; }
    virtual void f1() { cout << "b1::f1()" << endl; }
    virtual void f2() { cout << "b1::f2()" << endl; }
    virtual void f3() { cout << "b1::f3()" << endl; }
private:
    string _sname1;
};
class b2 : virtual public a {
public:
    b2(const char* saname, const char* ssname)
        : _sname2(saname), a(ssname) {
        cout << "b2::ctor" << endl;
    }
    b2(const b2& b2) : a(b2) { cout << "b2::copy ctor" << endl; }
    ~b2() { cout << "b2::dtor" << endl; }
    virtual void f3() { f1(); cout << "b2::f3()" << endl; }
private:
    string _sname2;
};
class c : public b1, public b2 {
public:
    c();
    c(const c& c);
    ~c() { cout << "c::dtor" << endl; }
    virtual void f1() { a::f1(); cout << "c::f1()" << endl; }
    void f3() { cout << "c::f3()" << endl; }
};

在虚拟继承的情况下,构造函数和析构函数的情况更加复杂。虚基类a的构造函数和析构函数也应该在c类中调用,因为编译器不能在b1b2中选择在c对象中构建(唯一的)a部分。对于析构函数,编译器处理调用b1的析构函数、b2的析构函数和a的析构函数。

所以你应该实现

class c : public b1, public b2 {
public:
  c() : b1("", ""), b2("", ""), a("") {}
  c(const c& src) : b1(src), b2(src), a(src) {}
};

一般来说,在没有必要的时候应该尽量避免虚拟继承。但是这是一个很好的练习来理解它是如何工作的