无法从函数返回结构

时间:2011-09-14 19:04:51

标签: c++ function struct

我想让函数返回一个struct。因此,在我的头文件中,我定义了struct和函数签名。在我的代码文件中,我有实际的功能。我收到有关“未知类型名称”的错误。一切似乎遵循非常标准的格式。

为什么这不起作用?

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)

}

2 个答案:

答案 0 :(得分:3)

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

}

答案 1 :(得分:2)

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

}