[英]Class inheritance and operator overloading
我正在通过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
);
}
}
operator+
Derivative
重载的返回部分不会编译:
/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.dPos
与sf::Vector2<float> operator +(const sf::Vector2<float>& left, const sf::Vector2<float>& right)
的调用兼容,因为dw::math::Vector2<float>
sf::Vector2<float> operator +(const sf::Vector2<float>& left, const sf::Vector2<float>& right)
dw::math::Vector2<float>
sf::Vector2<float>
通过继承是sf::Vector2<float>
。 然后,该表达式应该产生一个sf::Vector2<float>
,这要归功于dw::math::Vector2f
这要归功于我猜想的非显式构造函数。 我哪里错了? 我应该如何使其工作?
sf::Vector<T>
并非旨在用作派生类,因为更好的方法是编写自由函数来扩展sf::Vector<T>
,这对操作员而言是无缝的。 不幸的是,对于正常的函数调用,C ++不像C#那样支持扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.