c++继承:2次重载基类中的operator+在派生类中不能正常使用。

问题描述 投票:2回答:1

我基于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就能正常工作。

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

c++ inheritance operators overloading
1个回答
1
投票

问题是,当你添加 MyVectorMyVector, MyVector::operator+ ( const MyVector<T>& rhs) 匹配,但当你加入 dataVectordataVector, dataVector::operator+ (const U& val) 继承自 MyVector)变得更加匹配,因为它接受了 任何的东西,不一定是可以覆盖到的。T. 有几种可能的解决方案。

  1. 使 dataVector 类型ef,如 using dataVector = MyVector<int>,如果合适的话。
  2. 增加一个 operator+ 接受 dataVector;它可以使用显式转换来调用继承的操作符(如 *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或任何适当的东西)。)
© www.soinside.com 2019 - 2024. All rights reserved.