gpt4 book ai didi

c++ - 使用运算符 == 和 != 比较 C++ 中的不同类

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:33 25 4
gpt4 key购买 nike

我正在尝试比较 C++ 中不同类的对象。如果我删除 section3,一切正常。但我想知道如何编辑比较运算符 ==!= 以使其正常工作?我得到的错误是 “不匹配 'operator=='(操作数类型是 'Fruit' 和 'Plant')”

这是我的代码:

#include <iostream>
#include <string>
class Plant
{
public:
Plant(std::string name) : type_(name)
{ }

bool operator==(const Plant &that) const
{ return type_ == that.type_; }

bool operator!=(const Plant &that) const
{ return !operator==(that); }

void print()
{ std::cout << type_ << std::endl; }

protected:
std::string type_;
};

class Fruit: public Plant
{
public:
Fruit(std::string name, std::string taste)
: Plant(name)
, taste_(taste)
{ }

bool operator==(const Fruit& that) const
{
return ( (taste_ == that.taste_) && (Plant::operator==(that)) );
}

bool operator!=(const Fruit& that) const
{
return !operator==(that);
}

void print()
{
Plant::print();
std::cout << taste_ << std::endl;
}

private:
std::string taste_;
};


int main()
{
Plant a("Maple");
a.print();
Plant b("Maple");

if (a == b)
{
std::cout << "a and b are equal" << std::endl;
}
else
{
std::cout << "a and b are not equal" << std::endl;
}

Fruit c("Apple","sweet");
c.print();
Fruit d("Apple","sweet");

if (c == d)
{
std::cout << "c and d are equal" << std::endl;
}
else
{
std::cout << "c and d are not equal" << std::endl;
}

if (a == c)
{
std::cout << "a and c are equal" << std::endl;
}
else
{
std::cout << "a and c are not equal" << std::endl;
}

/* Section 3 */
if (c == a)
{ std::cout <<"c and a are equal\n"<< std::endl; }
else
{ std::cout <<"c and a are not equal\n"<< std::endl; }

if (a != c)
{ std::cout <<"c and a are not equal\n"<< std::endl; }
else
{ std::cout <<"c and a are equal\n"<< std::endl; }
return 0;
}

谢谢..

最佳答案

可以添加非成员函数,

bool operator==(Fruit const& f, Plant const& p)
{
return false;
}

bool operator!=(Fruit const& f, Plant const& p)
{
return !(f == p);
}

这将适用于 Plant 的一种子类型。这种方法不可扩展。如果您创建更多 Plant 子类型,则需要使用不同的方法。

关于c++ - 使用运算符 == 和 != 比较 C++ 中的不同类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33992010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com