簡體   English   中英

定義簡單結構 object

[英]Defining simple struct object

有這么簡單的代碼:

struct OurVertex
{
  float x, y, z;        // pozycja
  float rhw;            // komponent rhw
  int color;            // kolor
};

OurVertex verts[] = {
    { 20.0f, 20.0f, 0.5f, 1.0f, 0xffff0000, },
    { 40.0f, 20.0f, 0.5f, 1.0f, 0xff00ff00, },
    { 20.0f, 40.0f, 0.5f, 1.0f, 0xff00ff55, },
    { 40.0f, 40.0f, 0.5f, 1.0f, 0xff0000ff},
};

我收到一個錯誤:

 };
 ^
main.cpp:47:1: error: narrowing conversion of ‘4278255360u’ from ‘unsigned int’ to ‘int’ inside { } [-Wnarrowing]
main.cpp:47:1: error: narrowing conversion of ‘4278255445u’ from ‘unsigned int’ to ‘int’ inside { } [-Wnarrowing]
main.cpp:47:1: error: narrowing conversion of ‘4278190335u’ from ‘unsigned int’ to ‘int’ inside { } [-Wnarrowing]

對我來說最令人不安的是}; 錯誤線。 提供的代碼有什么問題?

對我來說最令人不安的是};

這只是提示,編譯器會在此位置准確檢測到錯誤。 有時這看起來是錯誤的,但在這種情況下,它在正確位置的定義末尾是完美的。

struct OurVertex
{
  float x, y, z;        // pozycja
  float rhw;            // komponent rhw
  unsigned int color;            // kolor << "unsigned" should fix your problem
};

0xff0000ff是一個unsigned int ,它不適合有signed int 因此,您只需按照上面給出的方式定義您的結構。

從評論中,附加問題:“編譯器如何知道值 0xff0000ff 是無符號整數”?

看看integer 文字 那里說:

integer 文字的類型是該值可以適合的第一個類型,

該表顯示了一個帶有“二進制、八進制或十六進制基數”的列。 對於像0xff0000ff這樣的值,您會看到unsigned int是第一個合適的值。

信息技術 — 編程語言 — C++ 2011

4.5 積分促銷

integer 轉換等級 (4.13) 小於 int 等級的 integer 轉換等級 (4.13) 小於 int 等級的 prvalue 可以轉換為 int 類型的源值 int 的所有 int 類型的值; 否則,源純右值可以轉換為 unsigned int 類型的純右值

因此,顏色字段的類型應該是 unsigned int 或 long 或 unsigned long 等。

暫無
暫無

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

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