【问题标题】:How to correctly forward declare struct with "using XXX"?如何使用“使用 XXX”正确转发声明结构?
【发布时间】:2020-05-15 10:11:28
【问题描述】:

有一个头文件“api.h”我必须使用,我可以修改它,但是其中的所有结构名称都太长并且可读性也较差它们的命名风格与我的项目不相似。

例如在文件“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”中实现它。 我尝试在“myclass.hpp”中添加struct ContraDef_t的前向声明,如下:

#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通过“错误:在'struct'之后使用typedef-name'using ContraDef_t = struct AVERYVERYLONGLONGNAMEOFSTRUCT1'...”

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

【问题讨论】:

    标签: c++ include typedef using forward-declaration


    【解决方案1】:

    仅将前向声明放在标头中并包含该标头:

    // 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"
    // ...
    

    【讨论】:

    • 感谢您的帮助!但我不想在“myclass.hpp”中包含“common.hpp”,因为我想让“myclass.hpp”尽可能简单。还有其他方法吗?
    • @Leon common.h 只有前向声明和using,你不能比这更“简单”
    • @Leon 你的common.h#include "api.h",我知道这是你不想在my_class.h 中包含的api.h。我不这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2021-05-15
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多