c++ - linux 指针、引用和方法

标签 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;

文件.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/

相关文章:

linux - 启动 Jenkins 服务器的最佳方式是什么

c - 带有 c 型类型转换的 GCC 警告

linux - 我怎样才能找到 main() 的返回地址在堆栈中的位置?

关于依赖注入(inject)和单元测试的C++问题

具有未使用变量的 C++ 异常

c++ - 是否可以使用 C++ 模板来控制代码生成?

linux - Wayland 全局指针位置

c++ - 输入Ctrl+Z结束朗读会出现循环错误

c++ - 类型检测器 `hasNestedType` 没有编译?

linux - 为什么它不起作用?如果bash中的指令