简体   繁体   中英

Typedef struct initialization

Consider this snippet:

#include <iostream>

typedef struct Test_ {
    float value1;
    float value2;
} Test;

int main()
{
    Test t = Test();
    std::cout << t.value1 << std::endl; // Prints 0 
    std::cout << t.value2 << std::endl; // Prints 0
}

What am I actually doing here Test t = Test(); (what is this called: Test() )? And is it possible to use this syntax to inilize the member values of Test to something else?

Or do I have to do something like Test t = Test{.value1 = 1, .value2 = 2}; to get different init values?

Edit: Perhaps I was a bit vague in what I was asking about. My question was basically what is this syntax: Test t = Test();

What you need is:

#include <iostream>

struct Test {
    float value1;
    float value2;
};

int main()
{
    Test t = {1, 2};
    std::cout << t.value1 << std::endl; // Prints 1. 
    std::cout << t.value2 << std::endl; // Prints 2.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM