我是c ++的新手,模板在语法方面肯定不友好。基本上,这里有一些我已经编写,测试和完成的功能。只是一个简单的问题,我已经花了好几个小时为我的矩阵类编写非成员运算符 - 重载,并且已经获得了所有类型的语法错误。那么,我从哪里开始呢?
这是我的myMatrix.h:
#ifndef MYMATRIX_H
#define MYMATRIX_H
#include <exception>
#include <vector>
#include <iostream>
using namespace std;
/* I'm using this matrix to store data */
template<typename T>
using twoD = std::vector<std::vector<T>>;
template<class T>
class Matrix{
private:
int rows;
int cols;
twoD<T> matrix;
protected:
void validSizeCheck(int rows, int cols);
public:
Matrix(int rows, int cols);
Matrix(int rows, int cols, twoD<T> newMatrix);
twoD<T> getMatrix();
int getRows();
int getCols();
void printMatrix();
void operator=(const Matrix<T> &);
Matrix<T> &operator+=(const Matrix<T> &);
Matrix<T> operator+(const Matrix<T> &);
Matrix<T> operator*(const Matrix<T> &);
Matrix<T> operator*(const T &);
};
这是我尝试过的一件事:
template <class T>
Matrix<T> operator-(const Matrix<T>& lhs,const Matrix<T>& rhs){
if(lhs.rows != rhs.cols || lhs.rows != rhs.cols{
throw exception();
}
Matrix tmp(lhs.rows, lhs.cols);
for(int i = 0; i < lhs.rows; i++){
for(int j = 0; j < cols; j++){
tmp.matrix[i][j] = lhs.matrix[i][j]+rhs.matrix[i][j];
}
}
return tmp;
}
显然那不起作用.. 那么我应该遵循的语法是什么?此外,这可能是一个非常愚蠢的问题,但非成员函数应该在头文件或.cpp文件中吗?到目前为止,我写的所有内容都在.h文件中,因为它们都是模板..
非常感谢任何帮助。
更新: 我终于得到了适用于课堂和课程的代码。功能声明,我补充说:
template<class T>
class Matrix{
private:
...
protected:
...
public:
...
template<class U>
friend Matrix<U> operator-(const Matrix<U>& lhs, const Matrix<U>& rhs);
};
这是函数定义:
template <class U>
Matrix<U> operator-(const Matrix<U>& lhs,const Matrix<U>& rhs){
if(lhs.rows != rhs.cols || lhs.rows != rhs.cols){
throw exception();
}
Matrix<U> tmp(lhs.rows, lhs.cols);
for(int i = 0; i < lhs.rows; i++){
for(int j = 0; j < lhs.cols; j++){
tmp.matrix[i][j] = lhs.matrix[i][j]-rhs.matrix[i][j];
}
}
return tmp;
}
工作完美,没有警告!感谢所有的帮助
答案 0 :(得分:4)
成员rows
,cols
是私有的。非类成员运算符必须是类的朋友。在课堂上声明它:
friend Matrix<T> operator-<>(const Matrix<T>& lhs,const Matrix<T>& rhs);
阅读本文以获取更多信息:Operator overloading : member function vs. non-member function?
此外,这可能是一个非常愚蠢的问题,但是非成员函数应该在头文件还是.cpp文件中?到目前为止,我写的所有内容都在.h文件中,因为它们都是模板。
你做得对,所有模板都必须在头文件中。以下是更多信息:Why can templates only be implemented in the header file?
答案 1 :(得分:4)
您需要在temp变量声明中再次使用模板参数:
template <class T>
Matrix<T> operator-(const Matrix<T>& lhs,const Matrix<T>& rhs){
if(lhs.rows != rhs.cols || lhs.rows != rhs.cols{
throw exception();
}
Matrix<T> tmp(lhs.rows, lhs.cols);
for(int i = 0; i < lhs.rows; i++){
for(int j = 0; j < cols; j++){
tmp.matrix[i][j] = lhs.matrix[i][j]+rhs.matrix[i][j];
}
}
return tmp;
}
(更改在第5行:Matrix<T> tmp(lhs.rows, lhs.cols);
)