c++ 实现类似 java 的 interface

需求 cpp 实现类似 java 的 interface 解决 interface 关键字 因为 interface 所有声明默认都是 public=,所以选择 =struct. #define interface struct; #define implements public 使用 #include "Interface.h" Interface IBar { public: virtual ~IBar(){} virtual int getBarData() const = 0; virtual void setBarData(int nData) = 0; }; class Bar :public BasicBar,implements IBar { public: Bar(int x=0) : BasicBar(x) { } ~Bar(){} virtual int getBarData() const { std::cout <<"Get Bar!"; return 0; } virtual void setBarData(int nData) { } }; class DataAccess { // Construction & Destruction public: DataAccess() { } ~DataAccess() { } static IBar* createBar() { //返回对象给IBar接口 return(new Bar()); } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //IBar *bar = new Bar(); IBar *bar = DataAccess::createBar(); bar->getBarData(); delete bar; return a....

2023-07-28 · 1 min · 143 words · RamLife

c++ impl 使用接口类

需求 cpp impl ? 解决 impl 使用接口类有两种方式: 接口类只是作为一个壳,需要什么都是直接调用原来的类来实现 接口类是使用虚函数,实现类通过继承来实现 代理类 代理类非常简单,下面这个 WeightProxy 就是壳,具体的实现都在 Weight 里面。 #ifndef WEIGHTPROXY_H #define WEIGHTPROXY_H #include <string> #include <memory> class Weight; class WeightProxy { public: WeightProxy(); ~WeightProxy(); std::string GetInfo(); std::unique_ptr<Weight> m_proxy; }; #endif // WEIGHTPROXY_H #include "Weightproxy.h" #include "Weight.h" WeightProxy::WeightProxy() : m_proxy(new Weight()) { } WeightProxy::~WeightProxy() = default; std::string WeightProxy::GetInfo() { return m_proxy->GetInfo(); } #include <iostream> // std::streambuf, std::cout #include "Weightproxy.h" int main () { WeightProxy w; std::cout << w....

2023-07-27 · 1 min · 207 words · RamLife