如何在模板中编写朋友(操作员)方法
How to write a friend (operator) method in a template?
因此,我正在尝试在模板类中超载操作员 。代码编译和运行,但在使用操作员 时崩溃。尝试了很多事情,我认为这是语法问题吗?任何意见,将不胜感激!
运算符=超载并有效。
matrix.h
template <int row, int col, class T = int>
class Matrix
{
int rows;
int cols;
T** mat;
public:
Matrix(int defVal = 0) {
rows = row;
cols = col;
memory();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = defVal;
}
~Matrix() {
del();
}
Matrix(const Matrix& other) {
*this = other;
}
const Matrix& operator=(const Matrix& other) {
if (&other != this)
{
rows = other.rows;
cols = other.cols;
del();
memory();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = other.mat[i][j];
}
return *this;
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < m.cols; i++)
{
for (int j = 0; j < m.rows; j++)
os << m.mat[i][j] << " ";
os << endl;
}
return os;
}
friend Matrix operator+(const Matrix& other, T num) {
Matrix temp = other;
for (int i = 0; i < temp.rows; i++)
for (int j = 0; j < temp.cols; j++)
temp.mat[i][j] += num;
return temp;
}
void memory(){
mat = new T * [rows];
for (int i = 0; i < rows; i++)
mat[i] = new T[cols];
}
void del(){
for (int i = 0; i < rows; i++)
delete[] mat[i];
delete[] mat;
}
};
main.cpp
int main() {
Matrix<4, 4> mat;
std::cout << mat << std::endl;
Matrix<4, 4> identity(1);
std::cout << identity + 3 << std::endl; //crashes here
return 0;
}
如果您需要代码的其他部分,请告诉我!预先感谢!
您的复制构造函数和分配看起来可疑,更改rows
和cols
后del
,而无需初始化任何内容。我希望它应该是
Matrix(const Matrix& other) : rows(0), cols(0), mat(nullptr) {
*this = other;
}
const Matrix& operator=(const Matrix& other) {
if (&other != this)
{
del(); // clean up first
rows = other.rows;
cols = other.cols;
memory();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = other.mat[i][j];
}
return *this;
}
顺便说一句,我根本不会在这里使用动态分配,而是
template <typename T, size_t rows, size_t cols>
class Matrix
{
std::array<std::array<T, cols>, rows> mat;
public:
Matrix(T defVal = {}) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = defVal;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix& m) {
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
os << m.mat[i][j] << " ";
os << std::endl;
}
return os;
}
friend Matrix operator+(Matrix other, T num) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
other.mat[i][j] += num;
return other;
}
// No need for any special members
};
相关文章:
- <<操作员在下面的行中工作
- 一位朋友将模板函数缩写为clang和gcc
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- 班级的朋友是不可接近的
- 与朋友声明相反
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- 比根<操作员
- 警告定义朋友操作员在名称空间内声明
- 如何在模板中编写朋友(操作员)方法
- 如何与朋友操作员一起在链表下面工作
- 如何在没有包含朋友的情况下使用过载操作员
- C 朋友操作员模板专业化
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 在模板类中专门定义错误的朋友操作员
- 朋友向成员操作员*的模板运营商*声明*
- 操作员的特定于朋友的模板实例化
- Apple Mach-O Linker(Id)在C++中生成操作员朋友函数时出错