[英]Trouble returning a struct from a function
我想让一个函数返回一个结构。 因此,在头文件中,我定义了结构和函数签名。 在我的代码文件中,我有了实际的功能。 我收到有关“未知类型名称”的错误。 一切似乎都遵循非常标准的格式。
任何想法为什么这不起作用?
测试类
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
是一个子类的TestClass
,和trashme
是的成员函数TestClass
,所以你需要限定它们:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.