グローバルオブジェクトを作成するための以下は、コンパイルエラーになります。
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;
#pragma hdrstop
class Tester;
void input();
class Tester
{
static int number = 5;
public:
Tester(){};
~Tester(){};
void setNumber(int newNumber)
{
number = newNumber;
}
int getNumber()
{
return number;
}
}
Tester testerObject;
void main(void)
{
cout << "Welcome!" << endl;
while(1)
{
input();
}
}
void input()
{
int newNumber = 0;
cout << "The current number is " << testerObject.getNumber();
cout << "Change number to: ";
cin >> newNumber;
cout << endl;
testerObject.setNumber(newNumber);
cout << "The number has been changed to " << testerObject.getNumber() << endl;
}
コンパイルエラーは次のとおりです。
1>------ Build started: Project: test, Configuration: Debug Win32 ------
1>Compiling...
1>test.cpp
1>.\test.cpp(15) : error C2864: 'Tester::number' : only static const integral data members can be initialized within a class
1>.\test.cpp(33) : error C2146: syntax error : missing ';' before identifier 'testerObject'
1>.\test.cpp(33) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>.\test.cpp(49) : error C2039: 'getNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>.\test.cpp(55) : error C2039: 'setNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>.\test.cpp(57) : error C2039: 'getNumber' : is not a member of 'System::Int32'
1> c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : see declaration of 'System::Int32'
1>Build log was saved at "file://c:\Users\Owner\Documents\Visual Studio 2008\Projects\test\test\Debug\BuildLog.htm"
1>test - 6 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
- ここで試みたように、グローバルクラスオブジェクトを正しく作成するにはどうすればよいですか。
- そして、「クラス内で初期化できるのは static const 整数データメンバーのみ」という問題を修正するにはどうすればよいですか
- 基本的に、これをコンパイルできるように残りのエラーを修正するにはどうすればよいですか?
ファイル スコープでグローバル クラス オブジェクトを宣言するのが好きです (ファイル スコープですべてのグローバルを宣言するのが好きです)。なぜなら、別のソース ファイルを作成して「extern」を実行しなければならない場合、それが非常に複雑になり、うまくいかないからです。ただし、最終的にはそれを行う方法を理解したいと思っています...私が見ているすべてのチュートリアルはコンパイルされないようですが、コンパイルされない限り、それを再作成する方法がわかりません!
これをコンパイルすることができれば、これを行う方法をうまく学ぶことができます。したがって、誰かが上記を文字通りコピーして Visual C++ Express 2008 に貼り付けて動作するように書き直すことができれば、最終的にそれを再作成する方法を理解できるようになります。これに対する修正を見て、私は非常に興奮しています! グローバルオブジェクトを正しく動作させることができないだけです! グローバルクラスオブジェクトの宣言に関するその他の情報...またはそのことに関するその他の情報は大歓迎です!