简体   繁体   中英

Forward declaration for struct and nested struct

Is any way to use forward declaration for struct X and Y which is nested as II need to use them in the hpp for some of the class members, but I would like to have them in the cpp because my hpp is included in many places Thank you so much for any help!

//F1.hpp
#ifndef F1_HPP_
#define F1_HPP_

struct X;

struct Y
{
  struct Y1
  {
    int y1;  
  };
  X x1;
};


class Y1
{
public:    
    void f(X x);
    void f2(Y::Y1 y1);
};

#endif  // F1_HPP_

//F1.cpp
#include "F1.hpp"
#include <iostream>

struct X 
{
    int x;
    int x2;
    int x3;
};


void Y1::f(X x)
{
    std::cout<<"-1-\n";
}

// main.cpp
#include <iostream>
#include "F1.hpp"
using namespace std;

int main()
{   
    X x;
    Y1 f1;
    f1.f(x);

    return 0;
}

Short Answer: No (as far as my c++ knowledge concern)

Why: First, if you want to declare a variable of any type you need to know the exact size of the type. That is why forward declaration is not enough BUT pointers. Because size of pointers are always the same no matter the data type, you can use forward declaration for pointers.

Nested Types: As far as I know of C++ we can't nest types with just variables BUT pointers. You can use pointers and forward declaration to nest types.

Maybe something like this:

struct Y
{
  struct Y1
  {
    int y1;  
  };
  X* x1;
};


class Y1
{
public:    
    void f(X* x);
    void f2(Y::Y1* y1);
};

We cannot have a nonstatic data member of incomplete type. In particular, with only a forward declaration for X , we cannot define a data member of type X as you've done inside F1.hpp . This can be seen from type :

Any of the following contexts requires type T to be complete:

  • declaration of a non-static class data member of type T ;

Better would be to create separate header and source file for each class and then include the header wherever needed/required as shown below :

Yfile.h

#ifndef F1_HPP_
#define F1_HPP_

#include "Xfile.h" //needed for X x1; data member
struct Y
{
  struct Y1
  {
    int y1 = 0;  
  };
  X x1;
};
#endif

Xfile.h

#ifndef X_H
#define X_H

#include <iostream>

struct X 
{
    int x = 0;
    int x2 = 0;
    int x3 = 0;
};

#endif

Y1file.h

#ifndef Y1_H
#define Y1_H
#include "Yfile.h"
//forward declarations for parameters 
struct X; 


class Y1
{
public:    
    void f(X x);
    void f2(Y::Y1 y1);
};

#endif

Y1file.cpp

#include "Y1file.h"
#include "Xfile.h"
#include "Yfile.h"
void Y1::f(X x)
{
    std::cout<<"-1-\n";
}
void Y1::f2(Y::Y1 y1)
{
    std::cout<<"f2"<<std::endl;
}

main.cpp

#include "Xfile.h"
#include "Y1file.h"
int main()
{   
    X x;
    Y1 f1;
    f1.f(x);

    return 0;
}

Working demo

The output of the above program is:

-1-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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