调用父类函数比较父子类

托梅克·卡沃夫斯基

我当时在做一门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> =,但这不是重点,这里的比较只是一个例子。

代词

免责声明:至少在进行比较时,最好不要在真实代码中完成此类操作。这只是一些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对象的静态类型对其进行比较因此,如果您有:

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比较中一样 该系统基于双重动态调度,有时也称为访客模式。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

函数调用父类方法而不是子类?

如何在父类的函数中调用子类的函数

为什么在父类之前调用子类的析构函数?

在父类和子类的构造函数中调用重写的方法

Django / Python:如何从子类中的父类调用函数?

OOPS概念父类而不是子类的调用函数

在python中从子类调用父类构造函数

在父类构造函数调用的方法中访问子类字段

在php中从子类到父类调用函数

重载的子类函数无法调用相似名称的父类

子类的oop调用父函数

从孙子类调用父类构造函数,调用父代或祖父母构造函数?

当我在子类中调用函数时,而是在调用父类函数

调用父类函数

调用子类方法而不调用父类

如何在Flutter中从子类函数调用父类函数

在静态子类中获取调用父类

检测子类是否已调用父类

父类可以调用子类方法吗?

父类中子类的c ++调用方法

试图在C ++中的子类中调用父类的受保护函数

使用父类的变量来调用子类中的函数[java示例中的多态]

MockK:验证是否使用父类的特定子类类型的参数调用函数

从java / kotlin中的父抽象类数组调用子类函数

有什么办法可以在JAVA中使用父类的对象来调用子类的构造函数?

python:如何针对MRO从子类对象调用父类的函数

比较javers中子类和父类的对象

为什么必须在Java中子类的参数化构造函数中调用父类的参数化构造函数?

调用父子构造函数