簡體   English   中英

無法轉換{...} <brace-enclosed initializer list> 結構

[英]could not convert {…} from <brace-enclosed initializer list> to struct

我之前使用過TDM-GCC-5.10,現在切換回4.9 MINGW-GCC並嘗試使用列表初始化時遇到奇怪的錯誤:

class Vector2
{
public:
    Vector2(float x, float y)
    {
        this->x = x;
        this->y = y;
    }
    float x = 0.f;
    float y = 0.f;
};

struct Test
{
    int x = 0;
    Vector2 v;
};

int main()
{    
    Test tst = {0,Vector2(0.0f,0.0f)}; //Error
    return 0;
}

錯誤:

main.cpp: In function 'int main()':
main.cpp:21:41: error: could not convert '{0, Vector2(0.0f, 0.0f)}' from '<brace-enclosed initializer list>' to 'Test'
         Test tst = {0,Vector2(0.0f,0.0f)}; //Error
                                         ^

我在兩個編譯器中都使用了C ++ 14。 怎么了?

問題出在這里:

struct Test
{
    int x = 0; // <==
    Vector2 v;
};

直到最近,默認成員初始化程序阻止該類成為聚合,因此您不能對它們使用聚合初始化。 Gcc 4.9仍然在這里實現舊規則,而gcc 5使用新規則。

你錯過了; 在您的類定義之后和在int x = 0 然后你得到了很多錯誤,顯然只考慮了最后一個錯誤。 但是你的編譯器很困惑,因為沒有定義Vector2 (由於缺少; )。

這編譯:

int main()
{
    class Vector2
    {
    public:
        Vector2(float x, float y)
        {
            this->x = x;
            this->y = y;
        }
        float x = 0.f;
        float y = 0.f;
    };

    struct Test
    {
        int x;
        Vector2 v;
    };

    Test tst = {0,Vector2(4,5)};
    return 0;
}

暫無
暫無

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

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