簡體   English   中英

C ++中的“ Y未命名類型”錯誤

[英]“Y does not name a type” error in C++

我不知道要搜索什么以找到對此的解釋,所以我問。
我有這段代碼報告錯誤:

struct Settings{
    int width;
    int height;
} settings;

settings.width = 800; // 'settings' does not name a type error
settings.height = 600; // 'settings' does not name a type error

int main(){
    cout << settings.width << " " << settings.height << endl;

但是,如果我將值賦值放在main中,它將起作用:

struct Settings{
    int width;
    int height;
} settings;

main () {
    settings.width = 800; // no error
    settings.height = 600; // no error

你能解釋一下為什么嗎?

編輯:
關於Ralph Tandetzky的答案,這是我的完整結構代碼。 您能告訴我如何像我的代碼片段結構一樣分配值嗎?

struct Settings{
    struct Dimensions{
        int width;
        int height;
    } screen;

    struct Build_menu:Dimensions{
        int border_width;
    } build_menu;
} settings;

您不能將分配放在C ++中函數的上下文之外。 如果您對有時看到=符號在函數上下文之外使用的事實感到困惑,例如:

int x = 42; // <== THIS IS NOT AN ASSIGNMENT!

int main()
{
    // ...
}

這是因為=符號也可以用於初始化 在您的示例中,您沒有初始化數據成員widthheight ,而是為其分配了一個值。

在C ++ 11中,您可以編寫

struct Settings {
    int width;
    int height;
} settings = { 800, 600 };

為了修復您的錯誤。 出現錯誤是因為您試圖在函數主體之外分配值。 您可以在函數外部初始化但不能分配全局數據。

編輯:

關於您的編輯,只需編寫

Settings settings = {{800, 600}, {10, 20, 3}};

由於繼承,我不是100%確信(如果可行)。 我建議在這種情況下避免繼承,並將Dimensions作為成員數據寫入Build_menu結構。 使用這種方式時,繼承遲早會給您帶來各種麻煩。 優先考慮組成而不是繼承。 當您這樣做時,它將看起來像

Settings settings = {{800, 600}, {{10, 20}, 3}};

暫無
暫無

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

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