C++ 在私有(private)成员数据类中使用 strcmp()

标签 c++ class private member strcmp

我正在为类做作业,但在编译这段代码时遇到了问题。我用过#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>对于 strcmpstd::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/

相关文章:

c++ - 在 C++ 中查找换行符

c++ - Protocol Buffer : C++ string with null characters inside

c++ - 警告 : Comparison between signed and unsigned integer expression

c++ - 是否可以更改C++程序本身的代码?

C++:当我的应用程序在随机位置崩溃时从哪里开始?

c++ - 如何从 C++ 中的 char* 获取 float ?

python - 最Pythonic的方式来处理(1)对象类型的一般属性和(2)该对象实例的单独属性

c# - 如何让方法调用同一个类中的另一个方法?

node.js - node.js 和 redis 中的私有(private) channel 。如何?

java - 为什么类的私有(private)成员可以在compareTo中访问?