假设我有一个Person类,它可以分为类子类Body,类Mind和class Spirit。
我可以通过什么方式构建类Person,以便它可以包含Body,Mind,Spirit的声明代码和实现代码?
-------------我之前曾说过像这样的问题----------------
关于C ++ 我有兴趣将#include example.h包含在其他代码中,即类。
我感兴趣的是能够将代码重构为标头,无论是实现代码还是其他标头代码。这主要是为了帮助我更容易理解构图。并且能够在概念上划分代码,甚至可以在类中进行划分。
例如,给定一个Pawn类(伪代码)
Pawn.h -----------------------------------
#pragma once
#include "GameEngine.h"
class Pawn;
{
//I wish to export these declarations into a separate header Pawn_ModelH.h
class Model;
class Model_1;
class Model_2;
//I wish to export these declarations into a separate header Pawn_CameraH.h
class Camera;
class Camera_1;
class Camera_2;
//I wish to export these declarations into a separate header Pawn_PropertiesH.h
float Property_1;
float Property_2;
float Property_3;
Pawn();
};
----结束Pawn.h
和Pawn.cpp -----------------------------
#include "Pawn.h"
#include "Modelclasses.h" //implementation of model relies on this
#include "Cameraclasses.h" //implementation of camera relies on this
#include "Propertyclasses.h" //implementation of property relies on this
Pawn::Pawn
{
//I wish to export this to a seperate Pawn_ModelC.h, preferrably with include //Modelclasses.h
Model=implementation;
Model_1=implementation;
Model_2=implementation;
//I wish to export this to a seperate Pawn_CameraC.h, preferably with include //Cameraclasses.h
Camera=implementation;
Camera_1=implementation;
Camera_2=implementation;
//I wish to export this to a seperate Pawn_PropertyC.h, preferably with include //Propertyclasses.h
Property=implementation;
Property_1=implementation;
Property_2=implementation;
}
----结束Pawn.cpp
我想结束只是
Pawn_Composition.h ------------------
#pragma once
#include "GameEngine.h"
class Pawn
{
#include "Pawn_ModelH.h"
#include "Pawn_CameraH.h"
#include "Pawn_PropertiesH.h"
Pawn()
};
----结束Pawn_Composition.h
和Pawn_Composition.cpp -----------------------------
#include "Pawn.h"
//the other needed includes are now in the component includes
Pawn::Pawn
{
#include "Pawn_ModelC.h" // with #include "Modelclasses.h"
#include "Pawn_CameraC.h" //with #include "Cameraclasses.h"
#include "Pawn_PropertiesC.h" //with #include "Propertyclasses.h"
}
----结束Pawn_Composition.cpp
有什么阻止我这样做的吗?是否有更好的实现类似的东西?
答案 0 :(得分:0)
我可以通过什么方式构建类Person,以便它可以包含Body,Mind,Spirit的声明代码和实现代码?
据我所知,您希望创建一个层次结构,您希望Person
成为基类,Body
,Mind
和Spirit
是子类,它是基类的更具体的实现。现在,我在第一个代码片段中看到你想要#inlcude
一些类并使用它们。我建议不利用此指令并制作不同模块的forward declarations。
但你也有其他选择。让我们以Person
给出的开头示例。如果Body
,Mind
和Spirit
是Person
具有的某些特定功能,您可以使用Mixins,您可以在其中“插入”这些不同的功能将类分类到Person
并使用它们的功能。
还要记住,头文件用于保存代码的声明(告诉我们我们正在做什么的接口,而你的cpp文件是告诉我们的实际实现我们如何做这些事情)