我正试图从std :: vector继承来产生用于处理数学向量和矩阵的小型可用类。
经过一些工作,这是我到目前为止所获得的成果的概述:
#include <vector>
template<typename T>
struct vec : public std::vector<T> {
using std::vector<T>::vector; // to inherit the constructors
vec(const std::vector<T> &v) :std::vector<T>(v) {}
//vec() :std::vector<T>() {} // it is needed?
vec &operator+=(const std::vector<T> &B) {
auto ib = B.begin();
for (auto i = this->begin(); i != this->end(); ++i, ++ib) {
*i += *ib;
}
return *this;
}
friend vec operator+(vec a, const vec &b) { return std::move(a += b); }
};
template<typename T>
struct matr : public vec<vec<T>>
{
using vec<vec<T>>::vec; // to inherit the constructors
matr transpose() const {
matr res(this->operator[](0).size(), vec<T>(this->size()));
for (size_t i = 0; i < res.size(); ++i)
for (size_t j = 0; j < res[0].size(); ++j)
res[i][j] = this->operator[](j)[i];
return std::move(res);
}
//matr(const std::vector<std::vector<T>> &M):vec<std::vector<T>>(M){}
T operator()(size_t i, size_t j) const {
return this->operator[](j)[i];
}
T &operator()(size_t i, size_t j){
return this->operator[](j)[i];
}
};
using namespace std;
int main() {
vec<int> W1 = { 1,2,3 }; // ok only if vec inherits constructors from vector
vector<int> W2 = { 1,2,3 }; // ok
vec<int> W3 = W2; // ok but I had to define a constructor in vec from vector
vec<vec<int>> M1 = { W1,W2 }; // ok only if vec inherits constructors from vector and explicit cast
vector<vector<int>> M2 = { W1,W2 }; // ok!
vector<vec<int>> M3 = { W1,W2 }; // ok!
matr<int> M3b = { W1,W2 }; // ok!
matr<int> M4 = { {1,2,3},{4,5,6},{7,8,9} }; // ok only if vec inherits constructors from vector
//vector<vector<int>> M5 = M4; // KO it works if matr is declared also public vector<vector<int>>
matr<int> M6 = M4+M4; // Ok but only if vec defines it's own constructor ¿?.
// Shouldn't matr inherit the operator+ from vec in any case?
matr<int> M7 = M1; // Ok but I had to define a explicit cast in vec
//matr<int> M8 = M2; // KO no idea
matr<int> M9 = M3; // Ok if v
matr<int> M10 = M9.transpose(); // Ok (std::move works)
vec<int> a = M10[2]; // OK but there are problems if multiple inheritance
int b = M10(1, 2); // OK idem
M10(1, 2) = 4; // OK idem
// b = M10[1,2]; // KO no idea as how to define it.
}
我的主要问题是如何使定义M5和M8的行工作而不打扰其他行。如果matr同时从vec<T>
和vector<vector<T>>
继承,则M5会进行编译,但是我有很多歧义问题。对于M8,我尝试在matr中创建构造函数没有成功,当我取消注释时,其他几行停止工作(至少M3b和M4)。
很长时间以来,我一直在使用C ++编写一些问题和算法的代码,但是我在课堂上的经验很少,而且我不是专业的程序员,所以很抱歉这很愚蠢。题。我正在将VC ++ 2017或G ++ 8.2与--std = gnu ++ 14一起使用,并且我始终尝试在两者中进行编译。