【发布时间】:2014-07-21 08:07:27
【问题描述】:
我遇到过一个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'不适用于静态成员函数, 然后我注意到A.h中的aAPI类没有私有成员数据,所以我认为在X.so中应该有代码声明aAPI私有成员数据,以保持createaAPI或RegisterU传递的数据!!
我想知道在我的情况下 a.cpp 如何返回指向 aAPI 的指针,然后如何在 a.cpp 中声明 aAPI 的私有成员数据?!
Edit :
Here comes the simple source for this case :
啊.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;
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
将完成演示! ....非常感谢!!!!
【问题讨论】:
-
某处必须引用
X.so包含的内容?没有头文件,这个库完全没用。 -
aAPI类是一个抽象类,它被用作继承的基础。在我看来,您应该检查传递给createAPI的字符串并使用它来确定您应该创建哪个子类。