【问题标题】:Using string in a class c++ outputs error在 C++ 类中使用字符串输出错误
【发布时间】:2013-04-21 12:35:06
【问题描述】:

我想创建一个使用字符串库的 C++ 类。这是我的源代码:

test.h:

#include <string>


class info {
public:
    // constructor
    info (string first_name, string last_name, int age);
    // deconstructor
    ~info ();



private:
    string first_name;
    string last_name;
    int age;

};

这是我的头辅助文件:test.cpp

#include <string>
#include "test.h"


info::info (string first_name, string last_name, int age) {
    this->first_name = first_name;
    this->last_name = last_name;
    this->age = age;

}
info::~info () {
}

但是它给了我语法错误:标识符“字符串”未定义

这是为什么呢?我对 C++ 数据结构有点陌生

另外,我正在编译这是 Visual Studio 2012

【问题讨论】:

  • 只要使用完全限定名称,std::string,无论您在哪里使用string。

标签: c++ string class


【解决方案1】:

您需要在string 之前添加std::,因为您使用的是限定名称(命名空间std 中的标识符)。

例如,您的构造函数应该如下所示:

info (std::string const& first_name, std::string const& last_name, int age);

【讨论】:

  • 我不建议使用using,尤其是在标题中
  • 在标头中使用 using 语句是不好的,因为您在包括该标头在内的所有文件中公开了类型。
  • 我已经更正了这个问题。我正在使用 而不是 但我仍然收到错误,但我会尝试。
  • @DragosRizescu 使用std::string 而不仅仅是string。
  • 它有效,我不知道为什么我必须使用'using std::string;',但是我会去热身。谢谢!
猜你喜欢
  • 2013-04-17
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2017-02-26
  • 2014-03-08
  • 2021-06-28
  • 1970-01-01
相关资源
最近更新 更多