开发者

linux pointers and references and methods

开发者 https://www.devze.com 2023-03-02 19:07 出处:网络
Sorry for destrubing. I have a problem: file.h #include开发者_如何学Go <string> class X { public:

Sorry for destrubing. I have a problem:

file.h

#include开发者_如何学Go <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;}

And now I have a test.cpp file. I create an .so file from file.cpp and file.h in 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);
}                                                                                                                                                                   


When you type fir->method(&tt); you pass the address of tt, which is a pointer. So you're passing a pointer to a pointer.

What you want to do is fir->method(*tt);. Which will in fact pass your pointed object as a reference (because "converting" a pointer to a reference is done by "dereferencing" the pointer). This implies that you change std::string method(X::Y *Y); with std::string method(X::Y &Y); in declaration and implementation. It means that whenever you pass an Y to your function, it will be in fact passed as reference and not value. It also means you have to access Y members with . and not ->.

0

精彩评论

暂无评论...
验证码 换一张
取 消