gpt4 book ai didi

c++ - 派生运算符 < 接收 Base 对象作为参数

转载 作者:行者123 更新时间:2023-11-30 03:28:13 25 4
gpt4 key购买 nike

我知道派生类"is"基类,因此您始终可以将派生对象传递给基类成员函数。现在,我特别想知道比较运算符的相反情况(基类不是抽象的并且有对象)。

假设我有:

class Base:
{
public:
Base(int m1, string m2);
virtual ~Base();
int GetM1()const;
string GetM2()const;

virtual bool operator<(const Base& base)const;

private:
int m1;
string m2;
};

我想做这样的事情:

class Derived: public Base
{
public:
Derived(string member);
~Derived();

virtual bool operator<(const Base& base)const; // is this possible(without cast)???

};

谢谢

最佳答案

是的,这是可能的。 Derived 运算符将在如下代码中使用:

Base b;
Derived d;
if (d < b) {
...
}

您还可以从 Base 派生一些其他类,例如 Derived1,它将被使用:

Derived1 d1;
Derived d;
if (d < d1) {
...
}

关于c++ - 派生运算符 < 接收 Base 对象作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46741494/

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