2.1 構造体、共用体、列挙体
2.1.1 構造体
#include <iostream>
struct product
{
int id;
int price;
int stock;
};
int main()
{
product pen;
pen.id = 0;
pen.price = 100;
pen.stock = 200;
product * ptr = &pen;
std::cout << "商品ID: " << ptr->id << std::endl;
std::cout << "単価: " << ptr->price << std::endl;
std::cout << "在庫数: " << ptr->stock << std::endl;
}
#include <iostream>
struct product
{
int id;
int price;
int stock;
};
int main()
{
product pen = {0,100,200};
product * ptr = &pen;
std::cout << "商品ID: " << ptr->id << std::endl;
std::cout << "単価: " << ptr->price << std::endl;
std::cout << "在庫数: " << ptr->stock << std::endl;
}
We have to write initial values in the same order as they are written in the struct definition.
#include <iostream>
struct product
{
int id;
int price;
int stock;
};
void show_product(struct product* ptr)
{
std::cout << "商品ID: " << ptr->id << std::endl;
std::cout << "単価: " << ptr->price << std::endl;
std::cout << "在庫数: " << ptr->stock << std::endl;
}
int main()
{
product pen = {0, 100, 200};
product *ptr = &pen;
show_product(ptr);
}
2.1.2 共用体
member variable are in the same address.
So, if we change any of them, other variables are changed.
#include <iostream>
union U
{
int a;
int b;
int c;
};
int main()
{
U u = {42};
std::cout << "u.aのアドレスは " << &u.a << std::endl;
std::cout << "u.bのアドレスは " << &u.b << std::endl;
std::cout << "u.cのアドレスは " << &u.c << std::endl;
}
2.1.3 enum
#include <iostream>
enum class category {
Value1,
Value2,
Value3 = 100,
Value4
};
int main()
{
category cat = category::Value4;
std::cout << static_cast<int>(cat) << std::endl;
}
列挙体変数が何バイト使うのかを決めるには、underlying-typeを指定する
enum class category : char {
Value1,
Value2,
Value3 = 100,
Value4
};
char type is 1 byte. So, in this case, the value of each enum is 0 <= and < 127.