编译错误C++

Compile error C++

本文关键字:C++ 错误 编译      更新时间:2023-10-16

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

主.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;
}

主.h-

#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include <string>
class strings
{
public:
    string getstr (string str);
};
#endif // MAIN_H_INCLUDED

错误-

error: 'string' does not name a type
error: no 'std::string strings::getstr(std::string)' member function declared in class 'strings'
error: In function 'int main()':
error: 'class strings' has no member named 'getstr'

我正在使用代码::块和 gcc我写了这个简单的代码,因为我正在处理一个项目,当我想编译时,我总是得到

"字符串"不命名类型

对不起,英语不好...

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

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

#include <string>
using namespace std;

就个人而言,我不喜欢使用"使用命名空间..."。(我很难跟踪不同的命名空间)。

这可以解决问题

#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include <string>
class strings
{
public:
    std::string getstr(std::string str);
};
#endif // MAIN_H_INCLUDED

标题后使用 using namespace std; main.h