2011-09-14 118 views
1

我想要一個函數返回一個結構體。所以,在我的頭文件中,我定義了結構和函數簽名。在我的代碼文件中,我有實際的功能。我收到有關「未知類型名稱」的錯誤。一切似乎都遵循一個非常標準的格式。從函數返回結構的麻煩

任何想法爲什麼這不起作用?

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

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 

} 
+0

他'trashme'函數是一個成員函數,所以它應該是合格的,他忘了在他回來:) –

+0

哇分號結尾,我瞎 –

+0

我答案是錯誤的。 –

3

foo是一個子類的TestClass,並且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 

}