linux指针以及引用和方法

时间:2011-05-05 07:46:17

标签: c++ linux

抱歉令人不安。你有一个问题:

file.h

#include <string>
class X
{
public:
    X();
    class Y
    {
    public:
        Y();
        std::string name;
    }*yy;
    std::string method(X::Y *Y);
}*xx;

file.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文件 在test.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);
}                                                                                                                                                                   

1 个答案:

答案 0 :(得分:0)

当您输入fir->method(&tt);时,您会传递tt的地址,这是一个指针。所以你要将指针传递给指针

您要做的是fir->method(*tt);。实际上,这会将您的指向对象作为参考传递(因为将指针“转换”为引用是通过“解除引用”指针来完成的)。这意味着您在声明和实现中使用std::string method(X::Y *Y);更改std::string method(X::Y &Y);。这意味着无论何时将Y传递给函数,它实际上都将作为引用传递而不是值。这也意味着您必须使用.而不是->来访问Y成员。