"字符串"未命名类型 - C++ 错误
'string' does not name a type - c++ error
我是C++的新手。我最近正在制作一个小程序,它使用单独文件中的类。我还想使用setter和getter(set&get)函数为变量赋值。当我运行程序时,编译器给了我一个奇怪的错误。它说"字符串"不命名类型。这是代码:
MyClass.h
#ifndef MYCLASS_H // #ifndef means if not defined
#define MYCLASS_H // then define it
#include <string>
class MyClass
{
public:
// this is the constructor function prototype
MyClass();
void setModuleName(string &);
string getModuleName();
private:
string moduleName;
};
#endif
MyClass.cpp文件
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;
MyClass::MyClass()
{
cout << "This line will print automatically because it is a constructor." << endl;
}
void MyClass::setModuleName(string &name) {
moduleName= name;
}
string MyClass::getModuleName() {
return moduleName;
}
main.cpp文件
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
MyClass obj; // obj is the object of the class MyClass
obj.setModuleName("Module Name is C++");
cout << obj.getModuleName();
return 0;
}
您必须在头文件中显式使用std::
命名空间作用域:
class MyClass {
public:
// this is the constructor function prototype
MyClass();
void setModuleName(std::string &); // << Should be a const reference parameter
// ^^^^^
std::string getModuleName();
// ^^^^^
private:
std::string moduleName;
// ^^^^^
};
在您的.cpp
文件中,您有
using namespace std;
这还可以,但应该更好
using std::string;
或者甚至更好的是也像在报头中那样显式地使用std::
作用域。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'