抱歉破坏了。我有一个问题:
file.h
#include <string>
class X
{
public:
X();
class Y
{
public:
Y();
std::string name;
}*yy;
std::string method(X::Y *Y);
}*xx;
文件.cpp
#include "file.h"
#include <iostream>
#include <string>
X::X()
{
yy= new X::Y();
}
X::Y::Y()
{
cout<<name<<endl;
}
std::string X::method(X::Y *Y)
{
return (Y->name);
}
extern "C" C* create_object(){ return new X;}
现在我有了一个 test.cpp 文件。我从 file.cpp 和 file.h 创建一个 .so 文件 在测试.cpp中:
int main()
{
void* handle= dlopen("file.so",RTLD_NOW);
X* (*create)();
void (*destroy)(X*);
create = (X*(*))dlsym(handle,"create_obj");
destroy = (void(*)(X*))dlsym(handle,"destory_obj");
X::Y* (*create1)();
void (*destroy1)(X::Y*);
create1 = (X::Y*(*))dlsym(handle,"create_obj");
destroy1 = (void(*)(X::Y*))dlsym(handle,"destory_obj");
X* fir = (X*)(create);
X:Y* tt = (X::Y*)create1();
tt->name="me";
fir->method(&tt); //I WANT TO SEND A REFERENCE TO THE X::Y object class. It is not working.
//No match function to call to "XX::method(XX::YY**); WHY. Can someone help me? THX
destroy(fir);
destroy(tt);
}
最佳答案
当您输入fir->method(&tt);
时,您将传递tt
的地址,它是一个指针。因此,您正在传递指向指针的指针。
你想要做的是fir->method(*tt);
。实际上,它会将您指向的对象作为引用传递(因为将指针“转换”为引用是通过“取消引用”指针来完成的)。这意味着您在声明和实现中将 std::string method(X::Y *Y);
更改为 std::string method(X::Y &Y);
。这意味着每当您将 Y 传递给函数时,它实际上都会作为引用而不是值传递。这也意味着您必须使用 .
访问 Y 成员,而不是 ->
.
关于c++ - linux 指针、引用和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5894323/