标题文件中的C 结构
C++ struct in header file
我对结构不太熟悉。但是我创建了这个:
test.h:
class test {
public:
struct Astruct
{
int age;
int weight;
};
struct Astruct& MethodOne();
};
和test.cpp:
#include "test.h"
test::test() {}
struct Astruct& test::MethodOne() {
Astruct testStruct;
// code to fill in testStruct
return testStruct;
}
以上代码的目标是我能够用MethodOne
返回struct
。
但在
的线上struct Astruct & test::MethodOne(){
它说:错误:声明与标题文件中的内容不相容。
我不明白这一点。如果我用int
返回类型替换结构,那不会出现错误吗?这里怎么了?
和我返回teststruct时我会遇到的第二个错误:错误:类型为" Ascruct&"的引用。(不合格)不能用类型的" test :: astruct"类型的值初始化
您的代码有多个错误(缺少;
等)。class
与C 中的struct
没有什么不同。唯一的区别是默认访问说明符,该指示符是class
中的private
和struct
中的public
(成员和继承)。
结构通常用于表明它实际上只是没有逻辑或方法的数据结构。恕我直言,它们很好地封装了方法的输入和输出。如果您想为会员函数提供它,它看起来可能是这样的:
class Foo{
public:
struct BarIn {}; // need ; here
struct BarOut {}; // and here
BarOut bar(const BarIn& b){return BarOut();}
};
int main() {
Foo::BarOut result = Foo().bar(Foo::BarIn());
}
请注意,我必须编写Foo:BarOut
和Foo::BarIn
,因为这些结构是在类内部声明的。另外,当您声明称为struct
的类型的变量时,无需编写struct
(因为class
或struct
的实例之间确实没有区别)。
最后但并非最不重要的是从不 struct Astruct & test::MethodOne(){
Astruct testStruct;
return testStruct; // testStruct is destroyed here
} // and the returned ref is invalid
- C++将文本文件中的数据读取到结构数组中
- 调用 C 文件中的"C++"结构
- 结构包含在两个头文件中,这两个文件我都不拥有
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 介子复制/安装头文件到输出目录并保持文件夹结构
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 将内部带有矢量的结构保存/读取到二进制文件中
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 将文本文件解析为树状数据结构
- 如何使用位字段将数据从二进制文件复制到结构中?
- 在树结构.txt文件中搜索节点
- 当结构位于单独的头文件中时'unregistered datatype'在 QML 中出现Q_GADGET错误
- 将文件读入数据结构
- 如何读取没有数组或结构的 3 列文件
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- 在.cpp文件之间传递结构声明,而不使用全局头文件
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 如何在结构/文件中搜索名称