Cri*_*sti 2 c++ operator-overloading
class matrix
{
int n;
double **a; //the "matrix"
public:
matrix(int);
~matrix();
int getN();
matrix& operator=(matrix&);
double& operator()(int,int);
friend matrix& operator+(matrix,matrix);
friend matrix& operator-(matrix,matrix);
friend matrix& operator*(matrix,matrix);
friend ostream& operator<<(ostream &,const matrix &);
};
matrix& operator+(matrix A,matrix B)
{
int i,j,n=A.getN();
assert(A.getN()==B.getN());
matrix *C=new matrix(A.getN());
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
(*C)(i,j)=A(i,j)+B(i,j);
}
}
return *C;
}
Run Code Online (Sandbox Code Playgroud)
这是重载算术运算符的正确方法吗?
我的代码中是否有内存泄漏?
的构造在堆分配内存,第一对的阵列双指针,则对于每个指针的阵列双.
你应该按值返回新的矩阵,并通过const引用传递(至少一个)参数:
matrix operator+(const matrix& A, const matrix& B);
Run Code Online (Sandbox Code Playgroud)
这意味着您不应该在运算符的主体内动态分配它.
如果只调用公共成员方法或成员运算符,则无需将非成员运算符声明为friend.
还要注意的是要实现普遍的做法+=,*=等为成员的运营商,然后实现非会员在这些方面:
matrix operator+(matrix A, const matrix& B)
{
return A+=B;
}
Run Code Online (Sandbox Code Playgroud)
另外,您必须检查矩阵的尺寸是否正确.使用您的设计,只能在运行时执行此操作.另一种方法是通过制作矩阵类模板在编译时强制执行维度正确性:
template <typename T, size_t ROWS, size_t COLS> matrix;
Run Code Online (Sandbox Code Playgroud)
权衡是不同维度的矩阵是不同的类型.
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |