我正在为类做作业,但在编译这段代码时遇到了问题。我用过#include <string>
在主 .cpp 文件和类 .cpp 文件中。错误是“‘strcmp’不是‘std’的成员”,但无论我使用 std::strcmp() 还是 strcmp() 都能得到它。
对我做错了什么有什么想法吗?
double temporary::manipulate()
{
if(!std::strcmp(description, "rectangle"))
{
cout << "Strings compare the same." << endl;
return first * second;
}
return -1;
}
最佳答案
您需要包括 <string.h>
或 <cstring>
对于 strcmp
或 std::strcmp
分别。 <string>
是 std:string
所需的 C++ 标准库及其他相关功能。
请注意 std::strcmp
需要两个 const char*
,不是 std::string
.如果description
是一个 std::string
,您可以使用 c_str()
获取指向基础数据的指针方法:
if(!std::strcmp(description.c_str(), "rectangle"))
或者只使用比较运算符。这是更惯用的解决方案:
if(description == "rectangle")
关于C++ 在私有(private)成员数据类中使用 strcmp(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21759751/