结构体和嵌套结构体的正向声明

  • 本文关键字:结构体 声明 嵌套 c++
  • 更新时间 :
  • 英文 :


是否有任何方法可以使用结构体X和Y的前向声明,因为我需要在hpp中为一些类成员使用它们,但我想让它们在cpp中,因为我的hpp包含在许多地方非常感谢你的帮助!

//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;
}

简短的回答:没有(就我对c++的了解而言)

原因:首先,如果您想声明任何类型的变量,您需要知道该类型的确切大小。这就是为什么前向声明是不够的BUT指针。因为无论数据类型如何,指针的大小都是相同的,所以可以对指针使用前向声明。

嵌套类型:就我所知的c++,我们不能嵌套类型,只有变量,但指针。您可以使用指针和前向声明来嵌套类型。

也许像这样:

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

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

我们不能有一个不完整的类型的非静态的数据成员。特别是,只有X的前向声明,我们不能像在F1.hpp中那样定义X类型的数据成员。这可以从type:

中看到

以下任何上下文都要求类型T是完整的:

  • 声明T类型的非静态类数据成员,

最好是为每个类创建单独的头文件和源文件,然后在需要/需要的地方包含头文件,如下所示:

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;
}

演示工作

上面程序的输出是:

-1-

最新更新