【发布时间】:2014-06-27 22:22:31
【问题描述】:
我似乎无法编译以下代码。如果我用 char * 替换所有字符串引用,它将编译并运行良好。我正在使用 Visual Studio 2013。我错过了什么?我花了几个小时试图弄清楚这一点。
这些是一些编译错误: 错误 1 错误 C2146:语法错误:缺少 ';'在标识符'ss'之前 c:\users\visual studio 2013\projects\class struct test\class struct test\class struct test.cpp 16 1 Class Struct Test
错误 2 错误 C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持 default-int c:\users\visual studio 2013\projects\class struct test\class struct test\class struct test.cpp 16 1 Class Struct Test
提前致谢。
#include "stdafx.h"
#include <iostream>
#include <string>
class test
{
public:
struct structType
{
int int1;
int int2;
string ss;
};
public:
int getint1();
int getint2();
string getString();
test()
{
privateVar.int1 = 5;
privateVar.int2 = 6;
privateVar.ss = "This is test string 1";
};
~test(){};
private:
structType privateVar;
};
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
test t;
cout << "Int 1: " << t.getint1() << endl;
cout << "Int 2: " << t.getint2() << endl;
cout << "String: " << t.getString() << endl;
};
int test::getint1() { return privateVar.int1;}
int test::getint2() { return privateVar.int2;}
string test::getString(){ return privateVar.ss; }
【问题讨论】:
-
std::string在命名空间内,而不是全局。您的代码示例可以简化为#include <string> string s;以演示相同的错误。编译器实际上也很漂亮helpful。 -
您在
_tmain之前有using namespace std。您可以将其移至文件顶部,或使用std::string。 -
string ss;应该是std::string ss; -
谢谢。将命名空间语句移动到文件顶部是我所缺少的。花了很多时间在谷歌上来理解这一点。
-
@user3784804,或者,take it out。