简体   繁体   English

如何在不同的文件中使用结构

[英]How do I use a struct in a different file

I have a struct S, declared in header1.h, that I need to use (as a vector) in header2.h and header2.cpp.我有一个在 header1.h 中声明的结构 S,我需要在 header2.h 和 header2.cpp 中使用(作为向量)。 I believe I have followed another similar example that already exists in the code, but I still get an error, and I do not understand why.我相信我遵循了代码中已经存在的另一个类似示例,但我仍然遇到错误,我不明白为什么。

This is basically the code:这基本上是代码:

header1.h header1.h

#pragma once

namespace NSP
{
struct S{
float a;
int b;
};

class KPR
{
void funfun(int a); //struct S is used in funfun
}

then I have header1.cpp然后我有 header1.cpp

#include "header1.h"
using namespace KPR;
using namespace std;

void KPR::funfun(int a)
{
S thisVec;
}

then I have header2.h然后我有 header2.h

#pragma once
#include "header1.h"
namespace NSP{
class header2
{
public:
header2(void);
~header2(void);
int func(NSP::S thisVec);
}
}

and of course header2.cpp当然还有 header2.cpp

#include "anotherHeader.h"  //(a bunch of includes, amongst others #include header1.h)
header2::header2(void){
}
header2::~header2(void){
}
int header2::func(NSP::S thisVec)
{
}

In other words,换一种说法,

I have followed the structure of another input argument of func which is also a struct, but declared in its own.h file (same namespace though).我遵循了 func 的另一个输入参数的结构,它也是一个结构,但在其 own.h 文件中声明(虽然名称空间相同)。 I have simplified the problem a bit by using NSP::S instead of std::vectorNSP::S But it is the same error: at this point, there is a red squiggle below func in the cpp file and the error message window displays func(.... thisVec...) instead of NSP::S thisVec.我通过使用 NSP::S 而不是 std::vectorNSP::S 简化了问题,但它是相同的错误:此时,cpp 文件中的 func 下方有一个红色波浪线,并显示错误消息 window func(.... thisVec...) 而不是 NSP::S thisVec。 I am left scratching my head as to why this happens, can someone please explain what is going on?我不知道为什么会这样,有人可以解释一下发生了什么吗?

The problem is that when implementing the member functions of class NSP::header2 , you're not in the scope of namespace NSP .问题是,当实现 class NSP::header2的成员函数时,您不在命名空间NSP的 scope 中。 Essentially you're implementing them(incorrectly) in global namespace.本质上,您是在全局命名空间中(错误地)实现了它们。 In other words, if you choose to define the member functions outside the class, then they must be implemented in the same namespace in which the class was defined .换句话说,如果您选择在 class 之外定义成员函数,那么它们必须在定义 class 的同一个命名空间中实现 This means they should be implemented in NSP and not global namespace.这意味着它们应该在NSP不是全局命名空间中实现。

To solve this replace header2::header2 with NSP::header2::header2 as shown below:解决此问题,请将header2::header2替换为NSP::header2::header2 ,如下所示:

#include "header2.h" 
vvvvv------------------------->added this 
NSP::header2::header2(void){
}
vvvvv------------------------->added this
NSP::header2::~header2(void){
}
int NSP::header2::func(NSP::S thisVec)
{
}

Working demo工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM