Home > Back-end >  How to use struct declared in header file from source file c ?
How to use struct declared in header file from source file c ?

Time:10-06

I have a header file (abc.hpp) as bellow:

#include <iostream>
#include <stdio.h>
#include <vector>
using std::vector;
class ABC {
public:
        struct BoxPoint {
            float x;
            float y;
        } ;
        vector<BoxPoint> getBoxPoint();

Then, in the source file (abc.cpp):

#include "abc.hpp"
vector<BoxPoint> ABC::getBoxPoint(){
   vector<BoxPoint> boxPointsl;
   BoxPoint xy = {box.x1, box.y1};
   boxPointsl.push_back(xy);
   return boxPointsl
}

When I compile, there is error:

error: ‘BoxPoint’ was not declared in this scope

at line vector<BoxPoint> ABC::getBoxPoint()

If I change to void ABC::getBoxPoint(), (also change in the header file and remove return boxPointsl, the error does not exist. Can you point me to why display the error and how to resolve it? Thank you!

CodePudding user response:

the symbol BoxPoint was only known inside ABC scope, outside you have to add the ABC scope, so ABC::BoxPoint:

#include "abc.hpp"
vector<ABC::BoxPoint> ABC::getBoxPoint(){
   vector<BoxPoint> boxPointsl;
   BoxPoint xy = {box.x1, box.y1};
   boxPointsl.push_back(xy);
   return boxPointsl
}

Inside the function you can use BoxPoint again, since we are inside the ABC scope again.

  • Related