gpt4 book ai didi

c++ - 派生类中virtual operator==的重新定义

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:42 25 4
gpt4 key购买 nike

我将要在派生类上重新定义运算符==。基类本身重新定义了operator==,即:

virtual bool operator==(const Dress &c) const {
return brand==c.brand && size==c.size
}

在这种情况下,我认为 brand==c.brandthis.brand==c.brand 相同。在我的派生类上,我使用相同的函数签名。

virtual bool operator==(const Dress &c) const

我的问题是:

使用检查参数类型是否匹配是否正确

typeid(this) == typeid(c)

因为这个重新定义的函数只会在派生类的元素上调用?我不明白的是,如何重新定义函数以在调用 derived_class_object == base_class_object 等对象时返回 false?

基类

class Dress {
private:
string brand;
int size;
public:
Dress(string b="unknown", int s=40): brand(b), size(s) {}
virtual bool operator==(const Dress &c) const {
return brand==c.brand && size==c.size
}

派生类

class Tshirt: public Dress {
private:
bool is_shortsleeve;
public:
Tshirt(string b="unknown", int s=40, bool t=true):Capo(b,s),is_shortsleeve(t) {}
virtual bool operator==(const Dress &c) const {

...

}

显然,除了其他控件之外,我还需要检查这两个元素是否属于派生类。像我之前写的那样做可以接受吗?

最佳答案

这就是您要找的吗?

#include <iostream>
#include <string>

class base
{
protected:
int a;
public:
base(int a) : a(a) {}
virtual bool operator == (base & other) const
{
return (typeid(*this) == typeid(other)) && this->a == other.a;
}
};

class derived : public base
{
public:
derived(int a) : base(a)
{}
virtual bool operator == (base & other) const
{
derived* otherDerived = dynamic_cast<derived*>(&other);
bool canBeCastToDerived = (0 != otherDerived);
bool isExactlyTheSameType = (typeid(*this) == typeid(other));
bool hasOtherProperties = false;

if (otherDerived)
{
hasOtherProperties = (this->a == otherDerived->a);
}

return canBeCastToDerived && isExactlyTheSameType && hasOtherProperties;
}
};

int main()
{
using std::cout;
base one(1);
derived two(2);

cout << (one == one) << "\n";
cout << (one == two) << "\n";
cout << (two == one) << "\n";
cout << (two == two) << "\n";
}

编辑 1:在评论中包含所有有效的批评。

编辑 2:更改示例以明确包含其他变体。

关于c++ - 派生类中virtual operator==的重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35018712/

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