从函数返回结构体时出现问题
Trouble returning a struct from a function
我想有一个函数返回一个结构体。因此,在我的头文件中,我定义了结构体和函数签名。在我的代码文件中,我有了实际的函数。我得到关于"未知类型名称"的错误。一切似乎都遵循一个非常标准的格式。
知道为什么这不起作用吗?
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
是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
}
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 我应该如何在C++中使用结构体解决输入失败的问题?
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 结构体向量的问题:解约束迭代器(可能很容易)
- 比较值与结构体成员的问题
- 结构体的重新定义错误.头文件的问题
- 从结构体到char *的转换问题
- 在ce5上从c#传递结构体并在非托管c++ dll中修改的问题
- c++中声明结构体的问题
- 从函数返回结构体时出现问题
- c++模板和结构体问题
- 从文本文件c++中加载结构体向量的奇怪问题