如何正确转发带有“使用XXX”的声明结构?

问题描述 投票:0回答:1

我必须使用头文件“ api.h”,并且可以NOT对其进行修改,但是其中的所有结构名称都太长且可读性较差,而且命名方式也为它们与我的项目不同。

例如在文件“ api.h”中:

#pragma once
struct AVERYVERYLONGLONGNAMEOFSTRUCT1 {
   ...
};
struct AVERYVERYLONGLONGNAMEOFSTRUCT2 {
   ...
};
...

因此,我创建了另一个标题“ common.h”,以便重命名它们。

文件“ common.hpp”:

#pragma once
#include "api.h"
namespace MyProject {
using ContraDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT1;
using AccountDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT2;
};

但是我只想将其包含在实现文件(* .cpp)中,而不是其他头文件中,因为我想加快编译过程。假设我在“ myclass.hpp”中声明一个类,并在“ myclass.cpp”中实现它。我尝试将结构ContraDef_t的前向声明添加到“ myclass.hpp”中,如下所示:

#pragma once
namespace MyProject {
struct ContraDef_t;
class MyClass_t {
   MyClass_t( const ContraDef_t * );
   ...
};
};

然后在“ myclass.cpp”中:

#include "common.hpp"
#include "myclass.hpp"
namespace MyProject {
MyClass_t::MyClass_t( const ContraDef_t * pcd ) {
   ...
};
};

最后,我可以NOT传递带有“错误:在type_name之后使用typedef-name'using ContraDef_t = struct AVERYVERYLONGLONGNAMEOFSTRUCT1'的编译”。

我该怎么办?任何帮助或提示将不胜感激!

c++ include typedef using forward-declaration
1个回答
2
投票

仅将前向声明放在标题中,并包括该标题:

// common.h
// dont include api.h here !
struct AVERYVERYLONGLONGNAMEOFSTRUCT1;
using ContraDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT1;

// my_class.h
#include "common.h"
struct my_class{ 
    ContraDef_t* c;
};

// my_class.cpp
#include "my_class.h"
#include "api.h"
// ...
© www.soinside.com 2019 - 2024. All rights reserved.