我遇到过一个c++ demo编程源码,里面有一个名为A.h的头文件,还有一个名为X.so的共享库,A.h如下:
#if !defined(A_H)
#define A_H
class aAPI
{
public:
static aAPI* createaAPI(const char*FlowPath = "");
virtual void Init() = 0 ;
virtual void Release() = 0 ;
virtual const char *GetDay() = 0;
virtual void RegisterU(char *pU) = 0;
protected:
~aAPI(){};
};
#endif
API类中的所有函数都是纯虚函数,所以不能用来创建对象, 这个 aAPI 的演示看起来像:
aAPI* ptr ;
ptr = aAPI::createaAPI("logtest");
strcpy(tradingDay, ptr->GetDay());
我正在尝试像这样编写 a.cpp 代码:
#include "a.h"
aAPI* aAPI::createaAPI(const char*FlowPath )
{
//return this ;
}
但我发现我无法返回 this,因为“this”对于静态成员函数不可用, 然后我注意到 A.h 中的类 aAPI 没有私有(private)成员数据,所以我认为在 X.so 中,应该有代码来声明类 aAPI 私有(private)成员数据以保持由 createaAPI 或 RegisterU 传递的数据!!
我想知道在我的例子中 a.cpp 如何返回指向 aAPI 的指针,然后如何在 a.cpp 中声明 aAPI 的私有(private)成员数据?!
Edit :
Here comes the simple source for this case :
啊啊
#if !defined(A_H)
#define A_H
class aAPI
{
public:
static aAPI* createaAPI(const char*FlowPath = "");
virtual void Init() = 0 ;
virtual void Release() = 0 ;
virtual const char *GetDay() = 0;
protected:
~aAPI(){};
};
#endif
a.cpp
#include "a.h"
#include "b.h"
aAPI* aAPI::createaAPI(const char*FlowPath)
{
static aAPI* ptr = 0x00 ;
if(ptr==0x00)
{
ptr = new bAPI(FlowPath) ;
}
return ptr;
}
b.h
#if !defined(B_H)
#define B_H
#include "a.h"
class bAPI:public aAPI
{
private:
char path[100] ;
char strday[11] ;
public:
bAPI(const char*FlowPath)
{
strcpy(path,FlowPath) ;
}
virtual void Init() ;
virtual void Release() ;
virtual const char *GetDay() ;
} ;
void bAPI::Init()
{
strcpy(strday,"2014/01/02") ;
}
void bAPI::Release()
{
}
const char* bAPI::GetDay()
{
return strday;
}
#endif
amain.cpp
#include "a.h"
using namespace std ;
int main()
{
aAPI* ptr = aAPI::createaAPI("hello world") ;
ptr->Init();
cout << ptr->GetDay() << endl ;
}
然后:
g++ --std=c++0x a.cpp amain.cpp -o amain.exe
将完成演示! ....非常感谢!!!!
最佳答案
header 指定共享库符合的接口(interface)。该库很可能包含派生自 aAPI
的类以及 aAPI
方法的实现。 static aAPI* createaAPI(const char*FlowPath = "")
是一个工厂方法 - 它实例化派生类并将它们作为指向基类的指针返回。
您可以通过从 aAPI
派生它们并实现抽象方法来创建符合接口(interface)的自己的类。但是,只要链接到 X.so
,就无法使用工厂方法创建派生类,因为不允许提供它的第二个实现。
关于C++ demo编程,混淆类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24860334/