【问题标题】:A string inside of a struct inside of a class [closed]类内部结构内部的字符串[关闭]
【发布时间】: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 &lt;string&gt; string s; 以演示相同的错误。编译器实际上也很漂亮helpful
  • 您在_tmain 之前有using namespace std。您可以将其移至文件顶部,或使用std::string
  • string ss; 应该是std::string ss;
  • 谢谢。将命名空间语句移动到文件顶部是我所缺少的。花了很多时间在谷歌上来理解这一点。
  • @user3784804,或者,take it out

标签: c++ string class struct


【解决方案1】:

您可能打算使用标准库字符串。它位于std 命名空间中。试试这个:

struct structType {
    int int1;
    int int2;
    std::string ss;
};

【讨论】:

  • 你是对的。这是一个命名空间问题。克里斯成功了。
【解决方案2】:

您可以在块的开头使用using namespace std

【讨论】:

  • -1 总的来说,这不是一个很好的建议。最好明确命名空间,或者使用 using 语句来消除本地使用的歧义(例如 using std::cout LocalStdout;
  • 感谢您的建议!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多