sblyat
sblyat

Reputation: 21

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. 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

#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

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

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

then I have 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

#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). 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. I am left scratching my head as to why this happens, can someone please explain what is going on?

Upvotes: 1

Views: 254

Answers (1)

user12002570
user12002570

Reputation: 1

The problem is that when implementing the member functions of class NSP::header2, you're not in the scope of namespace NSP. 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. This means they should be implemented in NSP and not global namespace.

To solve this replace header2::header2 with NSP::header2::header2 as shown below:

#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

Upvotes: 5

Related Questions