尝试比较字符串

Trying to compare strings

本文关键字:字符串 比较      更新时间:2023-10-16

我正在尝试将两个字符串与存储在map<string,IPHost> Address_list中的IP地址进行比较。我是C++新手,我认为我在头文件和实现文件方面做错了。这就是我到目前为止写的。当我编译它时,它说:

error: no matching function for call to 'IPHost::IPHost()`

有人可以指导我如何解决它吗?

这是我的头文件:

#ifndef IPHOST_H
#define IPHOST_H
#include <iostream>
class IPHost
{
    public:
        IPHost(int ip0, int ip1, int ip2, int ip3);
        bool checkIP(const IPHost&) const;
    private:
        int one;
        int two;
        int three;
        int four;
};
#endif

这是我的实现文件:

#include "IPHost.h"
#include <iostream>
#include <string>

using namespace std;
IPHost::IPHost(int ip0, int ip1, int ip2, int ip3 )
{
    ip0=one;
    ip1=two;
    ip2=three;
    ip3=four;
}

bool IPHost::checkIP(const IPHost& h)const
{
    if(one == h.one && two == h.two && three == h.three && four == h.four)
    {
        return true;
    }
    else
    {
        return false;
    }
}

我的主要功能:

#include <iostream>
#include <string>
#include <map>
#include "IPHost.h"
using namespace std;
int main
{
   map<string, IPHost> Address_list;
   Address_list["google.com"]=IPHost(74,125,225,20);
   Address_list["m.twitter.com"]=IPHost(199,16,156,43);
   if (Address_list["google.com"].checkIP(Address_list["m.twitter.com"]))
   {
      cout << "Two IP address are the same.n";
   }
   else
   {
      cout << "Two IP address do not match.n";
   }
return 0;
}

当你这样说时:

Address_list["google.com"]=IPHost(74,125,225,20);

std::map::operator[]默认构造一个IPHost对象,然后通过引用返回该对象,然后复制分配一个临时IPHost给这个对象。 编译器抱怨IPHost因为它没有默认构造函数,因此无法实例化std::map::operator[]方法实现。

(这是必需的,因为语法不允许std::map知道您尝试分配的值;它只知道您想要访问可能不存在的键"google.com",因此它需要创建一个IPHost对象,以便您可以为其分配值。 默认构造是唯一明智的选择。

如果要

使用此语法,则需要为 IPHost 提供默认构造函数:

public: IPHost();
// Later...
IPHost::IPHost() : one(0), two(0), three(0), four(0) { }

或者,您可以改用std::map::insert,这不需要值类型是默认可构造的,因为您直接提供IPHost对象用作值。

Address_list.insert(std::pair<std::string const, IPHost>(
    "google.com", IPHost(74,125,225,20)));

如果您有权访问 C++11,则可以通过使用 std::map::emplace 使此操作更高效、更不冗长

Address_list.emplace("google.com", IPHost(74,125,225,20));

请注意,如果已找到键,insertemplace 不会替换该值! 如果需要,您应该检查 insertemplace 调用的返回值,该值包含映射中元素的迭代器和指示它是否确实创建了该项的布尔值。 这样,它们在影响地图内容方面与a[b] = c语法并不完全相同。

如果您经常发现自己试图在映射中设置值而不考虑键是否已存在,我强烈建议您向IPHost添加一个默认构造函数,因为它将使更简单的a[b] = c语法成为可能,并防止您不得不编写更复杂的 if-item-已经存在-then-update-it-instead 情况。