不能将兄弟方法与虚拟继承 cpp 一起使用

Cant use brother methods with virtual inheritance cpp

本文关键字:cpp 一起 继承 虚拟 兄弟 方法 不能      更新时间:2023-10-16

由于虚拟继承,当 write(( 函数从 调用发射器类,方法从接收器类读取(( 被调用(您可能已经注意到,发射器类没有 有一个 read(( 函数(。在上面的层次结构中,我们可以实例化 只有无线电类,因为发射器和接收器是抽象的 到虚拟继承。 http://www.cprogramming.com/tutorial/virtual_inheritance.html

所以我尝试了一下,它对我不起作用。

#pragma once
#include <iostream>
using namespace std;

父亲类:

class father
{
public:
    father(){
    };
    ~father(){};
    virtual void printt() = 0;
    void sett()
    {
        printt();
    }
    void father()
    {
        cout << "Im your father...";
    }
private:
};

人:

#pragma once
#include <iostream>
using namespace std;
#include "father.h"
class MyClasst: public virtual father
{
public:
    MyClasst(){
        g = 8;
    };
    ~MyClasst(){};
    void print()
    {
        cout << "a";
    }
    void c()
    {
        cout << "bbb";
    }
private:
 ...
};

学生班:

#pragma once
#include <iostream>
#include "father.h"
using namespace std;

class MyClassa: public virtual father
{
public:
    MyClassa(){
    };
    ~MyClassa(){};
    void printt()
    {
        cout << "b";
    }
    void b()
    {
        c();
        printt();
    }
private:
...
};

根据上述规则,我应该能够在"b(("中从人员类调用"c(("("b(("是学生的函数,它是"人类"的虚拟兄弟(。但是我得到一个错误:

错误

1 错误 C3861:"c":标识符不是 找到 C:\users\micha\onedrive\מסמכים\Visual Studio 2013\项目\项目7\项目7\学生.h 21 1 项目7

这是因为 "c()" 函数没有在基类 "father" 中声明,而你的类 "MyClassa" 只派生自 "father"。因此,类 "MyClassa" 的对象将不包含任何函数 "c()"。从 "MyClasst" 派生的类的对象(以及从 "MyClassa" 和 MyClasst" 派生的对象将具有它(。如果要编译代码,必须在父类中添加"c()"的声明。在类"father"中添加行"virtual void c() = 0;",然后进行编译。这里活生生的例子:http://rextester.com/OBBC17077

没有

直接MyClassa c()的方法,也没有从father继承的方法。MyClasst中有一个方法c(),但是这两个类除了从father继承之外没有任何关系,但这不允许它们互相调用方法。

恕我直言,与所谓的"父类"和"子类"的类比没有多大意义,只会导致混淆。说"孩子是父母"是没有意义的,但这就是(公共(继承的实际含义。我建议你忘记"兄弟阶级"这个词。它无助于您理解任何事情。顺便说一句,您遇到的错误与virtual继承关系不大。public继承时,您会收到相同的错误。