C++ 继承运算符=

C++ Inheritance operator=

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

我知道这个问题以前有人问过;但是,我不明白解决方案。我正在尝试为 std::vector 创建一个子类,它能够独立成员函数(例如push_back(,但不能独立运算符(例如=(。 从这个例子来看,它似乎应该自动发生......向量类不同吗?

#include <iostream>
#include <vector>
using namespace std;
template <class T>
class FortranArray1 : public std::vector<T> {
public:
T & operator()(int row)
{
return (*this)[row-1];
}
};
int main()
{
vector <double> y;
y = {3};        // works
vector <double> z = y; //works
FortranArray1<double> x;
x = {3};        // doesn't work
x.push_back(3); // works
cout << y[0] << x[0] << ", " << x(1) ;
return 0;
}

您可以使用using来引入基类的operator=

template <class T>
class FortranArray1 : public std::vector<T> {
public:
using std::vector<T>::operator=;
T & operator()(int row){return (*this)[row-1];}
};

您可能还需要using std::vector<T>::vector;来介绍它的构造函数