C++ 继承:基类中重载 operator+ 的 2 次在派生类中无法正常工作

c++ inheritance: 2 times overloaded operator+ in base class are not working proper in derived class

本文关键字:常工作 工作 派生 基类 继承 重载 operator+ C++      更新时间:2023-10-16

我基于 std::valarray 编写了我的泛型类 "MyVector">

//myvector.h
#ifndef MYVECTOR_H
#define MYVECTOR_H
#include <valarray>
template <typename T> 
class MyVector
{
public:
MyVector(int size){larr.resize(size);}
MyVector<T>& operator=(const MyVector<T>& other) 
{
this->larr=other.larr;
return *this;
}
MyVector<T> operator+ ( const MyVector<T>& rhs);   //body in .cpp file
template <typename U> 
MyVector<T> operator+ (const U& val);              //body in .cpp file
protected:
std::valarray larr;
}
#endif
//myvector.cpp
/*****other code*****/
template <typename T>
MyVector<T> MyVector<T>::operator+ ( const MyVector<T>& rhs)
{
MyVector<T> lv; lv.larr = this->larr + rhs.larr;
return  lv;  
}
template <typename T>
template <typename U> 
MyVector<T> MyVector<T>::operator+ (const U& val)
{
MyVector<T> lv; lv.larr = this->larr + static_cast<T> (val);
return  lv;  
}
/*****other code*****/

然后我尝试编写一个派生类 DataVector,其中包含 MyVector 的所有函数,尤其是我所有的重载运算符。


#ifndef DATAVECTOR_H
#define DATAVECTOR_H
#include "myvector.h"
class dataVector : public MyVector<int>
{
public:
dataVector& operator=(const dataVector& other) 
{
this->larr=other.larr;
return *this;
}
using MyVector<int>::operator=;
using MyVector<int>::operator+;
}
#endif

当我尝试编译main.cpp时,

//main.cpp
#include "datavector.h"
#include "myvector.h"
dataVector datav1(10);
dataVector datav2(10);
dataVector datav3(10);
//if i write:
datav1=datav1 + 10;  //works (gmake and compiler gcc7.5 on ubuntu)
//if i write:
datav3=datav1 + datav2;  //does not work (gmake and compiler gcc7.5 on ubuntu)

我得到这个编译器错误:

myvector.cpp: In instantiation of ‘MyVector<T> MyVector<T>::operator+(const U&) [with U = dataVector; T = int]’:
myvector.cpp:xxx:yy: error: invalid static_cast from type ‘const dataVector’ to type ‘int’
MyVector<T> lv; lv.larr = this->larr + static_cast<T> (val);

如果我使用 MyVector:MyVector3=MyVector1+MyVector2 效果很好。

谁能帮我? 我知道这段代码写得不好,但我仍在学习。 谢谢。

问题是,当你将MyVector添加到MyVector时,MyVector::operator+ ( const MyVector<T>& rhs)匹配,但是当你将dataVector添加到dataVector时,dataVector::operator+ (const U& val)(继承自MyVector(成为更好的匹配,因为它接受任何东西,不一定是T隐蔽的东西。有几种可能的解决方案。

  1. 如果合适,dataVectorusing dataVector = MyVector<int>一样做一个 typedef。
  2. 添加一个接受dataVectoroperator+;它可以使用显式强制转换(如*this + (const MyVector<int> &)rhs(调用继承的运算符。
  3. MyVector::operator+ (const U& val)限制为仅接受T,如 Jarod42 所建议的那样。
  4. (艰难的方法(限制MyVector::operator+ (const U& val)只接受使用SFINAE的理智类型(如template <typename U, typename = typename std::enable_if<std::is_arithmetic<U>::value>::type>,或者is_convertible_to,或任何合适的(。