【发布时间】:2019-04-16 23:26:23
【问题描述】:
我有一个小问题。我有一个 Matrix 类定义如下(以行为主的形式):
template<typename T>
class Matrix {
private:
class RowVector {
private:
T *_vec;
std::size_t _l;
public:
RowVector(T *vec, std::size_t l);
const T &operator[](std::size_t index) const;
T &operator[](std::size_t index);
operator std::vector<T>() const;
};
std::vector<T> _data;
std::size_t _m;
std::size_t _n;
public:
Matrix(std::size_t m, size_t n, const T &elem = T());
const RowVector operator[](std::size_t index) const;
RowVector operator[](std::size_t index);
std::size_t getm() const;
std::size_t getn() const;
void fill(const T &elem);
void fillRow(std::size_t index, const T &elem);
void fillCol(std::size_t index, const T &elem);
Matrix &transpose(unsigned int i = 1);
const std::vector<T> &data() const;
};
并希望重载两个 RowVector 运算符=
typename Matrix<T>::RowVector &operator=(const std::vector<T> &vec);
typename Matrix<T>::RowVector &operator=(const Matrix<T> &mat);
所以我可以使用 A[0] 返回 RowVector & 并使用向量或矩阵重新分配其值。请记住,我(大概)可以忽略三个规则,因为我没有为客户端提供构造 RowVector 对象的明确方法。
但是,在尝试为重载编写函数体时,我遇到了一个问题:
(1) 我无法复制构造一个将在 operator= 范围之外持续存在的向量/矩阵对象,以便我可以将其 data() 分配给 _vec 并将其 size() 分配给 _l。
(2) 我不能直接修改_data,因为它不是静态变量;即使可以,我也无法找到索引,因此我可以覆盖封闭 Matrix 对象中的相关内存区域。
你知道有什么方法可以做到吗?这对我的班级来说是两个非常有用的资产。
我希望能够写出这样的东西:
Matrix<int> A(3, 4);
std::vector<int> v {1, 2, 3, 4};
Matrix<int> row(1, 4, 3);
// *****************
A[0] = v;
A[1] = row;
// *****************
(希望我的变量名是不言自明的) 我认为我的原型是正确的,但我就是找不到这样做的方法。
谢谢!
【问题讨论】:
-
为什么不在行类中使用 std::vector?
-
忽略三个规则:谁对您的行类中指向的数据拥有所有权(即谁负责删除它)?
标签: c++ oop vector reference operator-overloading