C++constオブジェクトとC constオブジェクトの違いの1つ-デフォルトの役割ドメイン
1408 ワード
アクティブドメイン
C++
グローバル役割ドメインで宣言されるconst変数は、オブジェクトファイルを定義するローカル変数です.
$ g++ main.cpp var.cpp /tmp/ccWHb099.o: In function `main': main.cpp:(.text+0x76): undefined reference to `MAX_TEST' main.cpp:(.text+0x7f): undefined reference to `FOO' collect2: ld returned 1 exit status
C
グローバル役割ドメインで宣言されるconst変数と非const変数の役割ドメインは同じです.
$ gcc main.c var.c
C++
グローバル役割ドメインで宣言されるconst変数は、オブジェクトファイルを定義するローカル変数です.
//var.c
extern const int MAX = 100; // extern const
const int MAX_TEST = 100; // construction
//main.cpp
using namespace std;
extern const int MAX;
extern const int MAX_TEST;
void foo()
{
const int FOO = 255; //
cout << "FOO=" << FOO << endl;
}
int main()
{
int x = MAX; //correct, const , extern
cout << "x = " << x << endl;
int y = MAX_TEST; //compile error, const ,
// 。NAX_TEST var.cpp
extern const int FOO;
int z = FOO; //compile error, const ,
// const
return 0;
}
$ g++ main.cpp var.cpp /tmp/ccWHb099.o: In function `main': main.cpp:(.text+0x76): undefined reference to `MAX_TEST' main.cpp:(.text+0x7f): undefined reference to `FOO' collect2: ld returned 1 exit status
C
グローバル役割ドメインで宣言されるconst変数と非const変数の役割ドメインは同じです.
//var.c
const int MAX = 1024;
//main.c
#include <stdio.h>
extern int MAX;
int main()
{
printf("MAX=%d
", MAX);
return 0;
}
$ gcc main.c var.c