如何在c ++中比较两个字符串并使用默认函数?

时间:2017-06-25 19:26:23

标签: c++

我正在研究我的第一个c ++代码,并且我有一些diffuclties strcmp函数无法解决!!即使我在h文件中做了:using std::string;我正在使用Eclipse,所以我在h文件中做了一个h和cpp文件我有这个:

#include <iostream>
#include <string>
#include <set>

using std::set;
using std::string;

namespace AA{
namespace BB{


    typedef enum{
        EASY , MEDIUM, HARD
    } Difficulty;

    class FIRST{
    private:
        char* name;
        Difficulty difficulty;

    public:       
        FIRST(const std::string& name, const Difficulty& difficulty);

        FIRST(const FIRST& first) = default;




    };
} // end of namespace BB
} 

// end of namespace AA

并且在cpp文件中我做了这个,但我感到很恐怖

  

无法解析函数strcmp'strcmp'不是'std'的成员

#include <iostream>
#include <string>
#include <set>
#include "Enigma.h"
#include <stdbool.h>

AA::BB::FIRST(const std::string& name, const Difficulty& difficulty):
    difficulty(difficulty),  name(name) {
}


bool AA::BB::FIRST::operator==(const FIRST& first) const{
    if((difficulty==(FIRST.difficulty))&&(strcmp(name,first.name)==0)){
        return true;
    }
    return false;
}

3 个答案:

答案 0 :(得分:2)

为什么要与strcmp进行比较,何时可以使用现有的==运算符:

bool AA::BB::FIRST::operator==(const FIRST& first) const{
    if((difficulty == FIRST.difficulty) && (name == first.name)){
        return true;
    }
    return false;
}

或者你可以使用它的比较函数产生相同的结果:

bool AA::BB::FIRST::operator==(const FIRST& first) const{
    if((difficulty == FIRST.difficulty) && (name.compare(first.name) == 0){
        return true;
    }
    return false;
}

答案 1 :(得分:0)

当您想要使用某个功能时,可以转到某个reference site,找出应该包含哪个标头以便使用此功能(在这种情况下为<cstring>)然后包含它。

您还应该弄清楚您正在使用的代码样式。 CAPS名称通常仅用于宏(因为它们是邪恶的)。

答案 2 :(得分:-2)

函数strcmp是C.没有字符串,因为你从C ++中知道它们。 见这里:http://www.cplusplus.com/reference/cstring/strcmp/

你可以这样做:

#include <string>

int main()
{
    std::string name = "Webber";
    std::string firstName = "John";

    if (strcmp(name.c_str(), firstName.c_str()) == 0)
        ...
}

这会将您的C ++ String复制到char-Array