当构造函数用于默认参数时如何定义和声明结构?

How to define and declare a struct when the constructor is used for a default argument?

我里面有一个 .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;
};

这里回答的是:

Private structures for that file should go in the .c file, with a declaration in the .h file if they are used by any functions in the .h .

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

似乎没有一种声明结构的方法只是为了转发声明它?

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

那么我是只在头文件中保留结构的声明和定义,还是有其他推荐的方法?

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

如果你使用

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