gpt4 book ai didi

c++ - 在 C++ 中,如何在派生类中重载二元运算符?

转载 作者:太空狗 更新时间:2023-10-29 23:02:14 25 4
gpt4 key购买 nike

我是 C++ 新手,这是我在练习编码时遇到的问题。假设我有一个看起来像的基类

class base {
public:
base();
friend base operator+(const base& lhs, const base& rhs) {
base result;
//some calculation
return result;
}
};

和派生类

class derived : base {
public:
derived();
friend derived operator+(const derived& lhs, const derived& rhs) {
// what to write here?
}
}

有没有一种简单的方法可以在两个派生类对象之间重载 + 运算符?基本上一切都会一样,除了我想要

derived result;

代替

base result;

在第一行中,以便派生类的构造函数负责对象的一些额外初始化。这似乎是一个常见的多态性特征,我想一定有一种优雅的方式来做到这一点,但我不确定如何......

非常感谢!

尼科

最佳答案

实现 operator+() 时遇到很多问题,你必须处理具有基类和派生类。

我能想到的最好的方法是实现一个virtual operator+=() 成员返回对您正在调用的对象的引用的函数功能开启。

struct base
{
// The usual other functions...
virtual base& operator+=(base const& rhs) = 0;
};

// Provide an implementation in the base class that
// takes care of what can be taken care of in the base
// class.
// This is allowed even when the function is pure
// virtual.
base& base::operator+=(base const& rhs)
{
// Do the needful.
// Return a reference to this object.
return *this;
}

struct derived : base
{
virtual base& operator+=(base const& rhs)
{
// Add checks to make sure that rhs is of
// derived type.

// Call the base class implementation to take
// care of updating base class data.
base::operator+=(rhs);

// Take care of updating the data of this object.

// Return a reference to this object.
return *this;
}
};

然后你可以使用:

base* bPtr1 = new derived;
base* bPtr2 = new derived;
(*bPtr1) += (*bPtr2);

关于c++ - 在 C++ 中,如何在派生类中重载二元运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29247109/

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