<目次>
(1) C++の「::」の記載の意味について
(1-1) 「::」の意味は?
(1-2) サンプル①:スコープ演算子「::」を使ってグローバル変数にアクセス
(1-3) サンプル②:スコープ演算子「::」を使って関数にアクセス
(1-4) 補足
(1) C++の「::」の記載の意味について
C++で「XXXXXX::YYYYY()」のような記述を見たことがありますでしょうか?今回はこの「::」の意味についてご紹介します。
(1-1) 「::」の意味は?
Fruits::Banana()
(1-2) サンプル①:スコープ演算子「::」を使ってグローバル変数にアクセス
#include <iostream>
#include <string>
using namespace std;
//# グローバルな変数
int age = 21;
int main() {
//# ローカルな変数
int age = 18;
cout << "グローバル変数の値:" << ::age << endl;;
cout << "ローカル変数の値:" << age << endl;;
return 0;
}

(1-3) サンプル②:スコープ演算子「::」を使って関数にアクセス
#include
#include
using namespace std;
//# 親クラス
class Fruit {
//# 親クラス内のメソッド
public:
static void calcPrice(int amount) {
cout << "フルーツの値段:" << amount * 100 << endl;
}
};
//# 親クラスを継承したクラス
class Apple : public Fruit {
//# 親クラスを継承したクラス内のメソッド
public:
static void calcPrice(int amount) {
cout << "リンゴの値段:" << amount * 200 << endl;
}
};
int main() {
Fruit::calcPrice(5);
Apple::calcPrice(5);
return 0;
}
