Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编译错误C++ 我是C++新手。当我编译此代码时,编译器会报告错误-_C++_String_Compilation - Fatal编程技术网

编译错误C++ 我是C++新手。当我编译此代码时,编译器会报告错误-

编译错误C++ 我是C++新手。当我编译此代码时,编译器会报告错误-,c++,string,compilation,C++,String,Compilation,main.cpp- #include <iostream> #include <string> #include "main.h" using namespace std; string strings::getstr(string str) { return str; } int main() { strings strstr; string constr; string msg; msg = "Hello World!"

main.cpp-

#include <iostream>
#include <string>
#include "main.h"

using namespace std;

string strings::getstr(string str)
{
    return str;
}

int main()
{
    strings strstr;
    string constr;
    string msg;

    msg = "Hello World!";
    constr = strstr.getstr(msg);
    cout << constr;
    return 0;
}
我正在使用Code::Blocks和gcc 我写这段简单的代码是因为我正在做一个项目,当我想编译的时候,我总是

“string”未命名类型


抱歉英语不好…

这可以解决问题

#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED

#include <string>

class strings
{
public:
    std::string getstr(std::string str);
};

#endif // MAIN_H_INCLUDED

string类的正确名称为“std::string”,因为它是在“std”命名空间中声明的,而“cout”也是如此。将“string”更改为“std::string”并使用“std::cout”而不是“cout”后,程序将正确编译

另一种方法是将“std”作为第一个命名空间:

#include <string>
using namespace std;

就个人而言,我不喜欢使用“使用名称空间…”我很难跟踪不同的名称空间。

使用名称空间std;在main.h中的头之后,使用std::string而不是string。和std::cout而不是cout.Check我会把答案放进去,但这绝对是一个重复。使用名称空间std不会使std成为默认名称空间,因为这个概念在语言中不存在。在头文件中这样做也是一个糟糕的主意。
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED

#include <string>

class strings
{
public:
    std::string getstr(std::string str);
};

#endif // MAIN_H_INCLUDED
#include <string>
using namespace std;