简体   繁体   English

试图从另一个C ++类返回一个类对象

[英]Trying to return a class object from another class C++

Hello I've been trying to return an object from a class but for some reason, whenever I try to return it, it fails but all other surrounding code works perfectly. 您好,我一直在尝试从类中返回一个对象,但是由于某种原因,每当我尝试返回它时,它都会失败,但是所有其他周围的代码都可以正常工作。

emp.h emp.h

class drvr{
private:
    string title;
    string empname;
public:
    drvr(string titlez, string name){
    title = titlez;
    empname = name;
    }

node.h 节点

class node{
private:
    drvr edata(string, string);
    node * next;
public:
    node(emp rec){
       edata(rec);
       next = NULL;
    }
   drvr getData(){
   return edata;
   }

I get the error: 我得到错误:

cannot convert 'node::data' from type 'drve (node::)(int, std::__cxx11::string) {aka drvr (node::)(int, std::__cxx11::basic_string)}' to type 'drvr'| 无法将类型'drve(node ::)(int,std :: __ cxx11 :: string){aka drvr(node ::)(int,std :: __ cxx11 :: basic_string)}'的'node :: data'转换为输入'drvr'|

You are declaring edata as a member function of class node that takes two arguments of type std::string and returns drvr object , but inside getData you are returning the address of that function , so the compiler tells you that the type of the object you are returning does not much what it expects this method to be returning as a type , obviously that's not what you want to do . 您将edata声明为类node的成员函数,该成员函数接受两个std::string类型的参数并返回drvr object,但是在getData内部,您将返回该函数的地址,因此编译器会告诉您该对象的类型返回值与该方法作为一种类型返回的期望值没有太大关系,显然这不是您想要执行的操作。 i can see from the code that you are coding a linked-list , so edata should be of type drvr and it should be defined like this : drvr edata; 我从代码中看到您正在编码一个linked-list ,因此edata的类型应为drvr ,并且应按以下方式定义: drvr edata;

And for setting a value for that attribute you can add a method to node : 为了为该属性设置值,您可以向node添加一个方法:

void setEdata(const drvr & d )
{
this->edata = d;
}

or 要么

void setEdata(const std::string & title,const std::string & empname )
    {
    this->edata = drvr(title,empname);
    }

When you say drvr edata(string, string); 当你说drvr edata(string, string); you are actually declaring a function named edata that returns a drvr and takes two string . 您实际上是在声明一个名为edata的函数,该函数返回drvr并使用两个string

To make it a variable initialized with string use {} . 要使其成为使用string初始化的变量,请使用{}

drvr edata{"hello", "world"};

Use like this: 像这样使用:

class drvr {
private:
    string title;
    string empname;
public:
    drvr(string titlez, string name) {
        title = titlez;
        empname = name;
    }
    drvr(const drvr& other)
    {
        title = other.title;
        empname = other.empname;
    }

};    

class node {    
private:
    drvr edata;
    node * next;
public:
    node(const drvr& rec)
        :edata(rec)
    {
        next = nullptr;
    }

    drvr getData()
    {
        return edata;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM