【发布时间】:2014-04-15 13:17:08
【问题描述】:
所以,我写了这个类,它看起来有点像这样:
class matrix
{
// Friends
friend ostream & operator << (ostream &os, const matrix &mat);
friend istream & operator >> (istream &is, matrix &mat);
private:
double *mdata;
int rows, columns, size;
后来我写了:
// Assignment operator
public:
matrix & operator=(const matrix &m) {
if(&m == this) {
return *this; // no self assignment
}
// First delete this object's array
delete[] mdata;
columns=0;
rows=0;
mdata=0;
int size=0;
// Now copy size and declare new array
size=m.getcols()*m.getrows();
if(size>0) {
mdata=new double[size];
// Copy values into new array
for(int i=0;i<size;i++) {
mdata[i] = m.mdata[i];
}
}
columns = m.getcols();
rows = m.getrows();
return *this; // Special pointer
}
我在课外有这个:
ostream & operator << (ostream &os, const matrix &mat) {
// Code goes here
os << "\n";
int j = 1;
for (int i=0; i < mat.size; i++) {
os << mat.mdata[i] << " ";
if (i+1 == j*mat.getcols()) {
os << "\n";
j = j + 1;
}
}
os << "\n";
os << "Wolfram|Alpha code:\n[[";
j = 1;
for (int i=0; i < mat.size; i++) {
os << mat.mdata[i];
if (i+1 != j*mat.getcols()){
os << ",";
}
if (i+1 == j*mat.getcols()) {
if (i+1 != mat.size) {
os << "],[";
}
else {
os << "]";
}
j = j + 1;
}
}
os << "] \n";
return os;
}
istream & operator >> (istream &is, matrix &mat) {
is >> mat.rows >> mat.columns;
int size(mat.rows*mat.columns);
if(size>0) {
cout << "Enter " << size << " values (top row, second row... last row - left to right)" << endl;
mat.mdata=new double[size];
// Copy values into new array
for(int i=0;i<size;i++) {
is >> mat.mdata[i];
}
}
return is;
}
但是在运行代码时(在 main 中):
cout << "Enter the rows and columns of a custom Matrix, row then column:" << endl;
matrix custom;
cin >> custom;
cout << custom;
cout << custom.getrows() << endl;
我没有打印出任何值...
Enter the rows and columns of a custom Matrix, row then column:
Default matrix constructor called
2
2
Enter 4 values (top row, second row... last row - left to right)
1 2 3 4
Wolfram|Alpha code:
[[]
2
Destructor called
关于我做错了什么有什么想法吗?完整代码here
编辑: 忘了说,我包括了赋值运算符,因为它有相同(或相似)的问题。
【问题讨论】:
标签: c++ class oop operator-overloading istream