gpt4 book ai didi

c++ - 基类方法的接口(interface)

转载 作者:行者123 更新时间:2023-11-30 05:34:05 25 4
gpt4 key购买 nike

对于下面的代码,还有其他方法可以通过接口(interface)访问基类中的方法吗?

struct Base {
void funct_base() {
printf("Common function for class Foo and class Bar\n");
}
};

struct IFoo {
virtual ~IFoo() {}
virtual void funct_a() = 0;
// would like to access Base::bunct_base() from here
};

struct Foo : public Base, public IFoo {
virtual void funct_a() {
printf("I am Foo:: funct A\n");
}
};

class IBar {
virtual ~IBar() {}
virtual void funct_a() = 0;
// would like to access Base::bunct_base() from here
};

class Bar : public Base, public IBar {
virtual void funct_a() {
printf("I am Bar:: funct A\n");
}
};

我知道这可以做到,但我就是不喜欢 wrapper ,它看起来不干净:

struct IBar {
virtual ~IBar() {}
virtual void funct_a() = 0;
virtual void funct_base() = 0;
};

struct Bar : public Base {
virtual void funct_a() {
printf("I am Bar:: funct A\n");
}

virtual void funct_base() {
Base::funct_base();
}
};

编辑:

问题是,有一个基类,以及继承自同一个基类的两个不同的派生类。有没有办法在不添加基类方法包装器的情况下通过派生类接口(interface)访问基类方法?

最佳答案

使用带有 Abstract method 的抽象基类 IBase funct_base 并将接口(interface)类设为 Virtual base classes BaseIFooIBar 类:

struct IBase {
virtual void funct_base() = 0;
};

struct Base : public virtual IBase {
virtual void funct_base() override { printf("Common function for class Foo and class Bar\n"); }
};

struct IFoo : public virtual IBase {
virtual void funct_a() = 0;
};

struct Foo : public IFoo, public Base {
virtual void funct_a() override { printf("I am Foo:: funct A\n"); }
};

class IBar : public virtual IBase {
virtual void funct_a() = 0;
};

class Bar : public IBar, public Base {
virtual void funct_a() override { printf("I am Bar:: funct A\n"); }
};

关于c++ - 基类方法的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34422859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com