【问题标题】:Calling parent class function to compare parent and child classes调用父类函数比较父类和子类
【发布时间】:2018-06-13 13:11:46
【问题描述】:

我正在学习 Python 课程,突然出现了使用父类覆盖函数来比较父类和子类的想法。基本上:

class A(object):
    def __init__(self,a):
        self.a = a

    def __lt__(self,other):
        return self.a < other.a

class B(A):
    def __init__(self,a,b):
        self.a = a
        self.b = b

    def __lt__(self,other):
        return self.b < other.b

a = A(2)
b = B(1,3)
print(a < b)
#print(b < a) # AttributeError: 'A' object has no attribuite 'b'
print(A.__lt__(b,a)) # so we call this instead

现在,我想在 C++ 中做同样的事情

class A{
    int a;
public:
    A(int a) : a(a) {}
    bool operator<(A t){ return a < t.a; }
};

class B: public A{
    int b;
public:
    B(int a, int b) : A(a), b(b) {}
    bool operator<(B t){ return b < t.b; }
};

int main()
{
    A a(2);
    B b(3,1);

    std::cout << (a < b) << std::endl;
    //std::cout << (b < a); // error, A has no b attribute
    //std::cout << A::operator<(dynamic_cast<A&>(b),a); // basically what I would like to happen
    std::cout << a.operator<(dynamic_cast<A&>(b)) << std::endl; // here I would like to reverse a and b

    return 0;
}

总得有个办法吧,不知道是不是对C++中的方法缺乏了解。

我知道我可以只重载 operator>=,但这不是重点,比较只是这里的一个示例。

【问题讨论】:

  • 如果您比较两个确实是B 对象的A&amp; 对象,您期望会发生什么? IE。 B x; A&amp; y = x; return y &lt; y;?它应该比较a 或b 的每个成员吗?
  • 如果我将x 投射到A&amp; 上,那么它应该通过A 类中定义的operator&lt; 来比较它们,所以通过a 属性来比较它们。其实你的问题帮我搞定了,我应该简单地将B对象投射到A&amp;上,然后调用它的操作员,即:dynamic_cast&lt;A&amp;&gt;(x) &lt; y
  • 进行这样的二进制操作在大多数情况下是没有意义和危险的。你可以实现你想要玩弄的东西并探索 C++ 是如何工作的,但是如果你用真实的代码来做,你会后悔的。只是不要。请给我们一个真实世界的例子,说明您正在尝试做什么。也许一个更好的设计选择是为了。
  • 这是一个纯粹的理论问题,因为同样的事情在 Python 中可以很容易地实现。

标签: python c++ class methods


【解决方案1】:

免责声明:最好不要在实际代码中完成此类事情,至少可以进行比较。这只是一些 C++ 结构的示例使用。

变体 1:静态调度。

class A{
    int a;
public:
    A(int a) : a(a) {}
    friend bool operator<(A& x, A& y){ return x.a < y.a; }
};

class B: public A{
    int b;
public:
    B(int a, int b) : A(a), b(b) {}
    friend bool operator<(B& x, B& y){ return x.b < y.b; }
};

这段代码根据 A 和 B 对象的 static 类型比较它们。所以如果你有:

B b(0, 42);
A& a = b;

a 在比较中的行为类似于A。该系统基于运算符重载。


变体 2:动态调度。

class A;
class B;

class A{
    int a;
public:
    A(int a) : a(a) {}
    virtual ~A() {}
    bool operator<(A& t){ return t.compare(*this); }
protected:
    virtual bool compare (A& t);
    virtual bool compare (B& t);
};

class B: public A{
    int b;
public:
    B(int a, int b) : A(a), b(b) {}
protected:
    bool compare (A& t) override;
    bool compare (B& t) override;
};

bool A::compare(A& t) { return t.a < a; }
bool A::compare(B& t) { return t.a < a; }
bool B::compare(A& t) { return A::compare(t); }
bool B::compare(B& t) { return t.b < b; }

此代码根据 A 和 B 对象的 动态 类型比较它们。所以如果你有:

B b(0, 42);
A& a = b;

a 在比较中的行为类似于B。该系统基于双重动态调度,有时也称为访问者模式。

【讨论】:

  • 谢谢,这回答了问题并给了我一些学习的东西。
猜你喜欢
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多