(C++) static constの使い方

今日も勉強になったので備忘録を残すことにしよう。

今日はC++のstatic constについて。

Javaのstatic finalとほとんど同じだろう?というつもりで書いたつもりが、なぜかVisual Studioに怒られる。

1>ConstTest.obj : error LNK2001: 外部シンボル “”public: static int const common::CommonValues::YEAR” (?YEAR@CommonValues@common@@2HB)” は未解決です。

こんな感じで。

意味不明だったけど大学院の先輩から後輩まで多くの方がTwitter上で助けてくれました。

とりあえず自分の書いたコードは以下の3つ

CommonValues.h

[cpp]
#pragma once

namespace common{

 class CommonValues
 {
 public:
 CommonValues(void);
 ~CommonValues(void);
 static const int YEAR;
 };

}
[/cpp]

CommonValues.cpp

[cpp]
#include "stdafx.h";
#include "CommonValues.h"

namespace common{

 const int YEAR = 365;

 CommonValues::CommonValues(void)
 {
 }


 CommonValues::~CommonValues(void)
 {
 }

}
[/cpp]

Main.cpp

[cpp]
#include "stdafx.h";
#include "CommonValues.h"
#include <iostream>

using namespace std;
using namespace common;

int main(){
 CommonValues c;
 cout << "start\n";
 cout << CommonValues::YEAR << endl;
}

[/cpp]

これをコンパイルすると上記のエラー。

答えはCommonValues.cppのconst int YEAR = 365;

これnamespace commonのグローバル変数になってんじゃねーか!(そう言うのかは知らんが)

正しくはconst int CommonValues::YEAR = 365;

またはそもそもそこに書かずにCommonValues.hの宣言部分を

static const int YEAR = 365;とする。

.hにまとめて書いた方がインライン展開されるのでコンパイラの最適化が効きやすいとかなんとか。ふむ、納得。

とにかくつまらないミスをしていただけだった・・。

Javaだと.hなんかに宣言分けずに一緒に書くから、今回のケースはすっかりハマってしまいました。今後は気を付けよう。

しかし今回のコンパイルエラーはなぜに未解決シンボルって出たんだろう。

Mainから見てYEARは名前解決できると思うんだけど。

でも、それはconstなのに値の定義が無くて・・・。だから.hで宣言されたconst変数の先が未解決ってことか・・・?

うーん・・・コンパイラは難しい。

とにかく今後もスキルを磨いていこう。


Posted

in

,

by

Tags:

Comments

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です