【问题标题】:How to define and declare a struct when the constructor is used for a default argument?当构造函数用于默认参数时,如何定义和声明结构?
【发布时间】:2019-07-07 15:57:17
【问题描述】:

我有一个 .h 文件,里面有一个函数,它使用 Struct/Class 构造函数作为默认参数。

它出现在声明结尾,就像在这里回答的那样:Where to put default parameter value in C++?

函数声明

vector<UINT_PTR> scan(const ScanOptions& scan_options = ScanOptions());

结构定义

struct ScanOptions {

ScanOptions()
{
    //Use some Windows.h functions here to find values
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    start_address = sysinfo.lpMinimumApplicationAddress;
    end_address = sysinfo.lpMaximumApplicationAddress;

}

UINT_PTR start_address;
UINT_PTR end_address;
};

这里的答案是:

该文件的私有结构应放在 .c 文件中,如果它们被 .h 中的任何函数使用,则应在 .h 文件中声明。

Should struct definitions go in .h or .c file?

似乎没有办法声明一个结构只是为了转发声明它?

C++, how to declare a struct in a header file

那么,我是否只是将我的结构的声明和定义保留在我的标题中,还是有其他推荐的方式?

我的意思是,自从它工作以来,我并不真正关心它的全球性,我认为它不会导致问题,但我真的很想知道。

【问题讨论】:

标签: c++ struct header declaration


【解决方案1】:

如果你使用

vector<UINT_PTR> scan(const ScanOptions& scan_options = ScanOptions());

在 .h 文件中,ScanOptions 的定义必须在函数声明处可见。

但是,您可以重载函数,而不是使用默认参数。

vector<UINT_PTR> scan();
vector<UINT_PTR> scan(const ScanOptions& scan_options);

理解第一个函数将使用默认构造的ScanOptions 来完成它的工作。通过该更改,您可以在 .h 文件中转发声明 ScanOptions 并仅在 .cpp 文件中定义它。

以下内容完全有效,不需要在.h 文件中定义ScanOptions

struct ScanOptions;

vector<UINT_PTR> scan();
vector<UINT_PTR> scan(const ScanOptions& scan_options);

【讨论】:

  • 哦,当然只是超载非常感谢,我现在觉得很愚蠢
  • @Ojav,没必要难过。这是旅程的一部分。您会在此过程中学习交易技巧。
猜你喜欢
  • 1970-01-01
  • 2014-07-05
  • 2012-07-19
  • 1970-01-01
  • 2015-10-30
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多