以下用于创建全局对象会导致编译错误。
#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 ==========
- 如何像我在这里尝试的那样正确创建全局类对象。
- 以及如何解决“只能在类中初始化静态 const 整数数据成员”
- 基本上我该如何修复其余的错误,以便编译它?
我喜欢在文件范围内声明全局类对象(我喜欢在文件范围内声明所有全局变量),因为当我必须创建单独的源文件并执行“extern”时,一切都会变得非常复杂,对我来说永远不起作用。虽然,我确实想最终弄清楚如何做到这一点......似乎我看到的每个教程都不会编译,除非它编译,否则我不知道如何重新创建它!
如果我可以编译它......那么我可以成功地学习如何做到这一点。因此,如果有人可以将上面的内容重写为它从字面上复制并粘贴到 Visual C++ Express 2008 中并且可以工作的地方,我最终将能够弄清楚如何重新创建它。看到这个问题的解决方案,我感到非常兴奋!只是我无法让全局对象正常工作!欢迎任何其他关于声明全局类对象的信息......或任何与此相关的信息!