(已解决)
如题:
我想把这个程序改成输入任意的维数的矩阵都能求其相加结果,但是改了以后发现程序运行时直接跳过了cin>>这个步骤,导致根本没有输入矩阵元素,现在不知道是因为构造函数问题还是重载运算符的问题,希望大神们看一下。
|
---|
问题是因为构造函数里没有对n赋值,因为其参数和字段重名了,所以很容易忽略掉!!! |
#include<iostream>
using namespace std;
class Matrix {
private:
double *m;
int n;
public:
Matrix(int n);
Matrix(double N[],int n);
~Matrix() {}
friend istream & operator >>(istream &input, Matrix &);
friend ostream & operator <<(ostream &output, Matrix &);
friend Matrix operator +(Matrix &A, Matrix &B);
};
Matrix::Matrix(int n) {
m = new double[n*n];
for (int i = 0; i < n*n; i++) {
m[i] = 0.0;
}
}
Matrix::Matrix(double N[],int n) {
m = new double[n*n];
for (int i = 0; i < n*n; i++) {
m[i] = N[i];
}
}
istream & operator >>(istream &input, Matrix &A) {
int n = A.n;
for (int i = 0; i < n*n; i++) {
input >> A.m[i];
}
return input;
}
ostream & operator <<(ostream &output, Matrix &A) {
int n = A.n;
for (int i = 0; i < n*n; i++) {
output << A.m[i];
if ((i + 1) % n == 0)cout << endl << endl;
else
{
cout << '\t';
}
}
return output;
}
Matrix operator +(Matrix &A, Matrix &B) {
int n = A.n;
double*t = new double[n*n];
for (int i = 0; i < n*n; i++) {
t[i] = A.m[i] + B.m[i];
}
return Matrix(t, n);
}
—————————————————————————————————————————————————————————————————————————————————————————
#include"matrix.h"
int main() {
puts("Input two matirx");
cout << "the dimension of the matrix:___\b\b";
int n;
cin >> n;
Matrix A(n), B(n);
puts("A:");
cin >> A;
puts("B:");
cin >> B;
puts("\nA+B is :");
Matrix C = A + B;
cout << C << endl;
system("color 3f");
system("pause");
}
#include<iostream>
using namespace std;
class Matrix {
private:
double *m;
int n;
public:
Matrix(int n);
Matrix(double N[],int n);
~Matrix() {}
friend istream & operator >>(istream &input, Matrix &);
friend ostream & operator <<(ostream &output, Matrix &);
friend Matrix operator +(Matrix &A, Matrix &B);
};
Matrix::Matrix(int dimension) {
n = dimension;
m = new double[n*n];
for (int i = 0; i < n*n; i++) {
m[i] = 0.0;
}
}
Matrix::Matrix(double N[],int dimension) {
n = dimension;
m = new double[n*n];
for (int i = 0; i < n*n; i++) {
m[i] = N[i];
}
}
istream & operator >>(istream &input, Matrix &A) {
int n = A.n;
for (int i = 0; i < n*n; i++) {
input >> A.m[i];
}
return input;
}
ostream & operator <<(ostream &output, Matrix &A) {
int n = A.n;
for (int i = 0; i < n*n; i++) {
output << A.m[i];
if ((i + 1) % n == 0)cout << endl << endl;
else
{
cout << '\t';
}
}
return output;
}
Matrix operator +(Matrix &A, Matrix &B) {
int n = A.n;
double*t = new double[n*n];
for (int i = 0; i < n*n; i++) {
t[i] = A.m[i] + B.m[i];
}
return Matrix(t, n);
}
_________________________________________________________________________________________
#include"matrix.h"
int main() {
puts("Input two matirx");
cout << "the dimension of the matrix:___\b\b";
int n;
cin >> n;
Matrix A(n), B(n);
puts("A:");
cin >> A;
puts("B:");
cin >> B;
puts("\nA+B is :");
Matrix C = A + B;
cout << C << endl;
system("color 3f");
system("pause");
}