データ型の基本概念
データ型はプログラミングにおいて情報の種類と表現方法を定義します。メモリ配置や操作方式を決定し、値範囲やメモリサイズなどの属性を含みます。
基本データ型
C++の基本データ型には以下の種類があります:
- 整数型:int, short, long, long long
- 浮動小数点型:float, double
- 文字型:char
- 論理型:bool
複合データ型
複合データ型には次のようなものがあります:
- 配列:同種要素の集合
- 構造体:異なる型のメンバーを含むユーザー定義型
- クラス:データと操作をカプセル化
型修飾子
データ型の属性を変更する修飾子:
- const:初期化後の変更不可
- unsigned:非負値専用
- signed:正負値対応
型変換の方法
C++では暗黙的変換と明示的変換が可能です。
キャスト演算子
// static_castの例
int val = 42;
double ratio = static_cast<double>(val);
// dynamic_castの例
class Base {};
class Derived : public Base {};
Base* base = new Derived;
Derived* derived = dynamic_cast(base);
// const_castの例
const int limit = 100;
int* modifiable = const_cast(&limit);
// reinterpret_castの例
int data = 0xABCD;
char* bytes = reinterpret_cast(&data);
標準ライブラリ関数
#include <cstdlib>
#include <string>
int main() {
// 文字列から整数変換
const char* text = "2048";
int converted = std::atoi(text);
std::string num_str = "4096";
int modern_conv = std::stoi(num_str);
}
型安全性の重要性
C++は静的型付け言語であり、コンパイル時に型が決定されます。
int counter = 5;
char symbol = 'X';
// 型不一致によるエラー
symbol = counter; // コンパイルエラー発生
変数の概念と使用
変数はデータを格納するための名前付きメモリ領域です。
変数の宣言と初期化
int quantity; // 宣言
quantity = 10; // 代入
double price = 24.99; // 宣言と初期化
スコープと寿命
変数は定義されたブロック内でのみ存在します。
命名規則
有効な変数名の例:
int user_count;
double _temperature;
無効な例:
int ユーザー数; // 非ASCII文字
double 123value; // 数字始まり
定数の特性
定数は初期化後に変更できない値です。
constキーワード
const double PI = 3.141592;
const int MAX_USERS = 100;
定数式
コンパイル時に計算可能な式:
constexpr int ARRAY_SIZE = 10 * 5;
実践例:円の計算
#include <iostream>
int main() {
const double PI = 3.14159;
double radius;
double area, perimeter;
std::cout << "半径を入力: ";
std::cin >> radius;
area = PI * radius * radius;
perimeter = 2 * PI * radius;
std::cout << "面積: " << area << '\n';
std::cout << "円周: " << perimeter << std::endl;
return 0;
}