簡體   English   中英

如何使用向量成員外部構造結構?

[英]How to extern const struct with vector members?

我將我的代碼拆分為聲明和定義。 在嘗試使用這個由向量組成的常量結構做任何事情之前,我沒有遇到任何問題。 將此代碼留在 header 中會導致多種定義類型的錯誤。

// Core.h:
const struct ConstData {
    vector<int> numbers1 = { 1, 2, 3, 4, 5 };
    vector<int> numbers2 = { 0, 10, 20, 30 };
} Constants;

我嘗試將這段代碼移動到 cpp 文件中,並在 header 中將extern與結構一起使用,但這沒有幫助。 在其他文件中結構字段的用例中,我遇到了未聲明的標識符類型的錯誤。

// Core.cpp:
const struct ConstData {
    vector<int> numbers1 = { 1, 2, 3, 4, 5 };
    vector<int> numbers2 = { 0, 10, 20, 30 };
} Constants;
// Core.h:
extern const struct ConstData Constants;

嘗試將帶有未初始化字段的結構放在extern之前。 認為這可能會有所幫助,因此編譯器會查看它正在使用哪種類型的結構以及它具有哪些字段。 但這被認為是重新定義,因為我在 cpp 文件中有相同的結構。

// Core.h:
const struct ConstData {
    vector<int> numbers1;
    vector<int> numbers2;
};

extern const struct ConstData Constants;
// Core.cpp:
const struct ConstData {
    vector<int> numbers1 = { 1, 2, 3, 4, 5 };
    vector<int> numbers2 = { 0, 10, 20, 30 };
} Constants;

我有點被困在這一點上。 查看人們如何處理這個問題並沒有讓我取得很大的成功。 在 Microsoft 的extern文檔中, const修飾符會更改鏈接類型(內部或外部)。 所以我再次嘗試了上述所有方法,但同時使用了const——沒有任何進展。 也許我錯過了什么..

希望我提供了足夠的信息,希望社區能夠幫助我!

這段代碼

const struct ConstData {
    vector<int> numbers1 = { 1, 2, 3, 4, 5 };
    vector<int> numbers2 = { 0, 10, 20, 30 };
} Constants;

...聲明結構類型ConstData和變量Constants 如果您已經在 header 文件中聲明了結構,則不能在.cpp文件中重新聲明該結構。

您想要拆分 header 中的兩個聲明,並且只初始化.cpp文件中的變量:

// Core.h
#include <vector>

struct ConstData {
    std::vector<int> numbers1;
    std::vector<int> numbers2;
};

extern const ConstData Constants;

// Core.cpp
#include <Core.h>

const ConstData Constants{
    { 1, 2, 3, 4, 5 },
    { 0, 10, 20, 30 }
};

我會推薦一個具有 static 個成員和std::array元素的結構。 由於 c++17 您可以在 header 文件中聲明:

#include <array>
struct ConstData {
    static constexpr std::array numbers1 = { 1, 2, 3, 4, 5 };
    static constexpr std::array numbers2 = { 0, 10, 20, 30 };
};

並使用ConstData::number1 / ConstData::number2

c++17之前需要付出更多的努力:

// Header file:
struct ConstData {
    static constexpr std::array<int, 5> numbers1 = { 1, 2, 3, 4, 5 };
    static constexpr std::array<int, 5> numbers2 = { 0, 10, 20, 30 };
};

// c++-File
constexpr std::array<int,5> ConstData::numbers1;
constexpr std::array<int,5> ConstData::numbers2;

這些是編譯時結構。 因此它們在 memory 中以 1:1 的比例出現。使用std::vector始終分配 memory 並在運行時復制元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM