从函数返回结构体时出现问题

Trouble returning a struct from a function

本文关键字:问题 结构体 函数 返回      更新时间:2023-10-16

我想有一个函数返回一个结构体。因此,在我的头文件中,我定义了结构体和函数签名。在我的代码文件中,我有了实际的函数。我得到关于"未知类型名称"的错误。一切似乎都遵循一个非常标准的格式。

知道为什么这不起作用吗?

TestClass.h

class TestClass {
public:
    struct foo{
        double a;
        double b;
    };
    foo trashme(int x);
}

TestClass.cpp

#include "testClass.h"
foo trashme(int x){
    foo temp;
    foo.a = x*2;
    foo.b = x*3;
    return(foo)
}

fooTestClass的子类,trashmeTestClass的成员函数,因此需要对它们进行限定:

TestClass::foo TestClass::trashme(int x){
    foo temp;  // <-- you don't need to qualify it here, because you're in the member function scope
    temp.a = x*2;  // <-- and set the variable, not the class
    temp.b = x*3;
    return temp;  // <-- and return the variable, not the class, with a semicolon at the end
                  // also, you don't need parentheses around the return expression
}

foo不在全局命名空间中,因此trashme()找不到它。你想要的是:

TestClass::foo TestClass::trashme(int x){ //foo and trashme are inside of TestClass
    TestClass::foo temp; //foo is inside of TestClass
    temp.a = x*2; //note: temp, not foo
    temp.b = x*3; //note: temp, not foo
    return(temp) //note: temp, not foo
}