我对结构不太熟悉。 但我创造了这个:
在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;
}
上述代码的目标是,我可以使用struct
返回MethodOne
。
但是
struct Astruct & test::MethodOne(){
它说:错误:声明与头文件中的内容不兼容。
我不明白这一点。如果我用int
返回类型替换结构,那么就不会有错误?
这有什么不对?
当我返回testStruct时出现第二个错误:错误:“Astruct&”类型的引用(不是const限定的)不能使用类型“test :: Astruct”
的值进行初始化答案 0 :(得分:3)
您的代码有多处错误(缺少;
等)。 class
与C ++中的struct
没有区别。唯一的区别是默认访问说明符,private
中的class
和public
中的struct
(成员和继承)。
结构通常用于表示它实际上只是一个没有逻辑或方法的数据结构。 Imho他们很高兴封装方法的输入和输出。如果你想将它用于成员函数,它可能如下所示:
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
或{{1}的实例之间确实没有区别}})。
最后但并非最不重要的是,永远不会将引用(或指针)返回到本地变量:
struct