在头文件中,我想添加我需要重载运算符的函数声明。然后实现我添加到头文件中的函数。
任何人都可以帮我解决我的想法吗?请解释一下,如果可能的话,我可以把头包裹起来。
我列出了以下代码。至于主要我不想编辑它。
头文件 Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
public:
Matrix (int sizeX, int sizeY);
~Matrix();
int GetSizeX() const { return dx; }
int GetSizeY() const { return dy; }
long &Element(int x, int y); // return reference to an element
void Print () const;
private:
long **p; // pointer to a pointer to a long integer
int dx, dy;
};
#endif /* MATRIX_H */
Matrix.cpp文件
#include <iostream>
#include <cassert>
#include "Matrix.h"
using namespace std;
Matrix::Matrix (int sizeX, int sizeY) : dx(sizeX), dy(sizeY)
{
assert(sizeX > 0 && sizeY > 0);
p = new long*[dx];
// create array of pointers to long integers
assert(p != 0);
for (int i = 0; i < dx; i++)
{ // for each pointer, create array of long integers
p[i] = new long[dy];
assert(p[i] != 0);
for (int j = 0; j < dy; j++)
p[i][j] = 0;
}
}
Matrix::~Matrix()
{
for (int i = 0; i < dx; i++)
delete [] p[i]; // delete arrays of long integers
delete [] p; // delete array of pointers to long
}
long &Matrix::Element(int x, int y)
{
assert(x >= 0 && x < dx && y >= 0 && y < dy);
return p[x][y];
}
void Matrix::Print () const
{
cout << endl;
for (int x = 0; x < dx; x++)
{
for (int y = 0; y < dy; y++)
cout << p[x][y] << "\t";
cout << endl;
}
}
的main.cpp
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <ctime>
#include "Matrix.h"
using namespace std;
int main(int argc, char** argv) {
int size1, size2, size3;
const int RANGE = 5; //using to generate random number in the range[1,6]
cout << "Please input three positive integers: (size)";
cin >> size1 >> size2 >> size3;
assert(size1 > 0 && size2 > 0 && size3 > 0);
Matrix myMatrix1(size1, size2), myMatrix2(size2,size3);
Matrix yourMatrix1(size1, size2), yourMatrix2(size2, size3);
Matrix theirMatrix1(size1, size2), theirMatrix2(size1, size3);
srand(time(0));
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
myMatrix1(i,j) = rand() % RANGE + 1;
yourMatrix1 = 2 * myMatrix1;
theirMatrix1 = myMatrix1 + yourMatrix1;
cout << "myMatrix1: " << endl;
cout << myMatrix1 << endl << endl;
cout << "yourMatrix1 = 2 * myMatrix " << endl;
cout << yourMatrix1 << endl << endl;
cout << "myMatrix1 + yourMatrix1: " << endl;
cout << theirMatrix1 << endl << endl;
for (int i = 0; i < size2; i++)
for (int j = 0; j < size3; j++)
myMatrix2(i,j) = rand() % RANGE + 1;
yourMatrix2 = myMatrix2 * 3;
theirMatrix2 = myMatrix1 * yourMatrix2;
cout << "myMatrix1: " << endl;
cout << myMatrix1 << endl << endl;
cout << "myMatrix2: " << endl;
cout << myMatrix2 << endl << endl;
cout << "yourMatrix2 = myMatrix2 * 3 " << endl;
cout << yourMatrix2 << endl << endl;
cout << "myMatrix1 * yourMatrix2: " << endl;
cout << theirMatrix2 << endl << endl;
return 0;
}
答案 0 :(得分:0)
您需要查看main并查看所有运算符与Matrix
对象一起使用的内容。您必须将这些运算符重载到给定的Matrix
类中,即将成员函数写入此类。
有关运算符重载的详细信息,请参阅以下链接:
http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading