【发布时间】:2020-05-10 17:45:53
【问题描述】:
我基于 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 效果很好。
谁能帮帮我? 我知道这段代码写得不好,但我还在学习。 谢谢。
【问题讨论】:
-
stackoverflow.com/questions/30138023/…>已经有答案了。
-
@stackoverblast 不,这个问题实际上并没有在基础中重载
operator+,而且它也没有模板化,这两者都与本示例相关。 -
cpp 中的模板代码可疑
-
你真的想要
template <typename U> MyVector<T> operator+ (const U& val);(匹配dataVector)而不是简单的MyVector<T> operator+ (const T& val);? -
谢谢大家,@Jarod42 我会尝试调整我的 .cpp 代码
标签: c++ inheritance operators overloading