关于linux下dynamic_cast无法正确转换的问题
如题.我的编程环境:ubuntu 6.06 g++4.03
我有一个类SubClass,继承于FatherOne,FatherTwo.产生一个libSubClass.so,接着在MainProgram.cpp中调用.
下面是所以的文件内容.
-------------SubClass.h----------------------------------
#include <iostream>
using namespace std;
#include "FatherOne.h"
#include "FatherTwo.h"
class SubClass : public CFatherOne, public CFatherTwo
{
public:
SubClass();
~SubClass();
virtual int init ();
virtual void ShowName();
};
-----------SubClass.cpp----------------------------------
#include "SubClass.h"
SubClass::SubClass(){}
SubClass::~SubClass(){}
int SubClass::init()
{
cout << "dll init!" << endl;
return 0;
}
void SubClass::ShowName()
{
cout << "this is a function from father two!" << endl;
}
extern "C" FatherOne* CreatClass();
FatherOne* CreatClass()
{
return new SubClass();
}
------------------FatherOne.h-----------------------
class FatherOne
{
public:
virtual ~FatherOne(){};
virtual int init(){return 0;};
};
------------------FatherTwo.h-----------------------
class FatherTwo
{
public:
virtual ~FatherTwo(){};
virtual void ShowName(){};
};
上面几个文件产生libSubClass.so
命令:g++ -shared -o libSubClass.so SubClass.cpp
----------------MainProgram.cpp-------------------
#include <dlfcn.h>
#include "FatherOne.h"
#include "FatherTwo.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
void *hDLL;
typedef CFatherOne* (*Creator)(void);
FatherOne *one;
hDLL = dlopen("./libSubClass.so",RTLD_NOW);
if (hDLL == NULL)
{
cout << "Loaded failed!" << endl;
return 1;
}
Creator creator;
creator = (Creator)dlsym(hDLL, "CreatClass");
if (creator == NULL)
{
cout << "Get function address failed!" << endl;
return 2;
}
one = creator();
if (obj == NULL)
{
cout << "Creating failed!" << endl;
return 3;
}
one->init();
(关键就是在下面这句,不能达到想要的目的)
FatherTwo* two = dynamic_cast<FatherTwo*>(one);
if (two == NULL)
{
cout << "Convertion failed!" << endl;
return 4;
}
two->ShowName();
return 0;
}
产生可执行文件:MainProgram
命令: g++ -ldl -o MainProgram MainProgram.cpp
说明: 如果不用动态连接库.直接在MainProgram.cpp中包含SubClass.h,执行下面的代码就能成功
FatherOne* one = new SubClass();
one->init();
FatherTwo* two = dynamic_cast<FatherTwo*>(one);
two->ShowName();
但是使用动态连接库才是我要用的.
还有就是这种写法, 在WINDOWS下面是行得通的.
请兄弟们帮助, 最好下载我的代码, 并实验. 万分感谢.
------解决方案--------------------g++ -ldl -o MainProgram MainProgram.cpp ?
似乎应该g++ -l ./libSubClass.so -o MainProgram MainProgram.cpp
------解决方案--------------------程序写的够乱的, 又是FatherOne, 又是CFatherOne的.