标题文件中的C 结构

C++ struct in header file

本文关键字:结构 文件 标题      更新时间:2023-10-16

我对结构不太熟悉。但是我创建了这个:

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中的privatestruct中的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:BarOutFoo::BarIn,因为这些结构是在类内部声明的。另外,当您声明称为struct的类型的变量时,无需编写struct(因为classstruct的实例之间确实没有区别)。

最后但并非最不重要的是从不

struct Astruct & test::MethodOne(){
    Astruct testStruct;
    return testStruct;            // testStruct is destroyed here
}                                 // and the returned ref is invalid