类继承和运算符重载

Class inheritance and operator overloading

本文关键字:重载 运算符 继承      更新时间:2023-10-16

我正在通过SFML上的一个小项目学习C++,我想扩展sf::Vector2<T>类,它代表一个2D数学向量。此类的声明可在此处获得。特别是,我想在类中添加一些方法,用于范数计算、旋转等。

这是我到目前为止所拥有的:

#include <cmath>
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Transform.hpp>
#include <ostream>
namespace dw::math {
template <typename T>
class Vector2 : public sf::Vector2<T> {
public:
// Don't really know what does that exactly means, explainations are welcome !
using sf::Vector2<T>::Vector2;
template <typename U>
explicit Vector2(const U &vector) : sf::Vector2<T>(vector) {}
// This ctor is for implicit conversion from base, don't know if it's really useful ?
Vector2(sf::Vector2<T> &vector) : sf::Vector2<T>(vector) {}
// Some methods here ...
friend std::ostream & operator<<(std::ostream &os, const math::Vector2<T>& right) {
os << '{' << right.x << ", " <<right.y << '}';
return os;
}
};

在代码的后面,我声明了这样一个结构:

struct Derivative {
dw::math::Vector2f dPos;
dw::math::Vector2f dVel;
Derivative() = default;
Derivative(const dw::math::Vector2f &dPos, const dw::math::Vector2f &dVel) : dPos(dPos), dVel(dVel) {}
Derivative operator+(const Derivative &rhs) const {
return Derivative(
dPos + rhs.dPos,
dVel + rhs.dVel
);
}
}

Derivativeoperator+重载的返回部分不编译:

/home/palra/Documents/Projets/dw/src/physics/World.cpp: In member function ‘Derivative Derivative::operator+(const Derivative&) const’:
/home/palra/Documents/Projets/dw/src/physics/World.cpp:24:18: error: invalid user-defined conversion from ‘sf::Vector2<float>’ to ‘const Vector2f& {aka const dw::math::Vector2<float>&}’ [-fpermissive]
dPos + rhs.dPos,
~~~~~^~~~~~~~~~
In file included from /home/palra/Documents/Projets/dw/src/physics/Body.h:8:0,
from /home/palra/Documents/Projets/dw/src/physics/World.h:10,
from /home/palra/Documents/Projets/dw/src/physics/World.cpp:5:
/home/palra/Documents/Projets/dw/src/physics/../math/Vector2.h:30:5: note: candidate is: dw::math::Vector2<T, <template-parameter-1-2> >::Vector2(sf::Vector2<T>&) [with T = float; <template-parameter-1-2> = void] <near match>
Vector2(sf::Vector2<T> &vector) : sf::Vector2<T>(vector) {}

我不明白为什么这不起作用。 表达式dPos + rhs.dPossf::Vector2<float> operator +(const sf::Vector2<float>& left, const sf::Vector2<float>& right)的调用兼容,因为dw::math::Vector2<float>是通过继承sf::Vector2<float>。然后这个表达式应该产生一个sf::Vector2<float>,由于我猜是非显式构造函数,它可以分配给dw::math::Vector2f。我错在哪里?我应该如何让它工作?

sf::Vector<T>

不是为了用作派生类而设计的,因为更好的方法是编写扩展sf::Vector<T>功能的自由函数,这对运算符来说是无缝的。不幸的是,对于普通函数调用,C++(还)不像 C# 那样支持扩展。