作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试比较 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/
所以我有这个 UltraTicTacToe 游戏,我正在用 HTML/CSS/JS 编码。它由表中表中的表组成。当您单击 X 或 O 时,我想要突出显示您应该进入的下一个 TicTacToe 牌 ta
Some text Some more text 如何让每个 .example 的 .whatever 包含其 .test 的内容? 例如,如果代码是这样的: Som
我是一名优秀的程序员,十分优秀!