简体   繁体   中英

Trouble returning a struct from a function

I want to have a function return a struct. So, in my header file, I defined the struct and the function signature. In my code file, I then have the actual function. I get errors about "unknown type name". Everything appears to be following a very standard format for this.

Any ideas why this isn't working?

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)

}

foo is a child class of TestClass , and trashme is a member function of TestClass , so you need to qualify them:

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 isn't in the global namespace, so trashme() can't find it. What you want is this:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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