定义并执行class Matrix(模拟一2x2输入整数的矩阵. Matrix class:
class Matrix{
public:
Matrix(int a1, int b1, int c1, int d1);
private:
int a, b, c, d;
};
Matrix::Matrix(int a1, int b1, int c1, int d1){
a = a1;
b = b1;
c = c1;
d = d1;
}
1.以公共成员函数重载以下操作: +=, -=, and *=.
Left operand is the calling object.以下操作应只包括right operand, return the left operand by reference by returning *this,the dereferenced this pointer which points to the calling object.
2.以非成员友元函数重载以下操作: <<, >>, +, -, *, ==,!=.用上步定义的+=, -=, *=重载+, -, * Create a local Matrix variable called temp which is a copy of the left Matrix object r,have temp use +=(e.g.)with the other Matrix s as the right operand,and then return the resulting Matrix temp by value.
3.重载指数算子^(友元函数).The left operand is a const Matrix& r (pass in by reference).The right operand is a const int n, which represents the power to which to raise the Matrix r. r^2 should return a copy of the matrix r*r(e.g.) Here is how it works:
1)n负,output an error message using the error output stream cerr which works like cout,then use the statement exit(1);terminates the program.The argument 1 indicates that an error forced program termination.
2)n为0,return an identity Matrix [a=1 b=0 c=0 d=1] by value.
3)否则,create a Matrix called temp which is a local copy of the parameter Matrix r passed in. Then create a loop that keeps multiplying temp by r and storing the result in temp until temp reaches the desired power of r. Then return temp by value.
4)Stream insertion << and extraction >> operators.Return the stream object at the end of each definition so that the operator can be chained like in the following statement: cout << m << n;
源代码顺序: Matrix的类定义,成员函数定义,友元函数定义,及以下定义将测试class:
int main(){
Matrix m(1, 2, 3, 4);
Matrix n(-1, 2, -3, 4);
cout << "Enter a 2x2 matrix with entries separated by spaces: ";
cin >> m;
cout << endl;
cout << "Enter another 2x2 matrix with entries separated by spaces: ";
cin >> n;
cout << "m: " << m << endl << "n: " << n << endl << endl;
cout << "m += n" << " = ";
m += n;
cout << m << endl << endl;
cout << "m -= n" << " = ";
m -= n;
cout << m << endl << endl;
cout << "m *= n" << " = ";
m *= n;
cout << m << endl << endl;
cout << "m: " << m << endl << "n: " << n << endl << endl;
cout << "m + n = "<< (m+n) << endl << endl;
cout << "m - n = "<< (m-n) << endl << endl;
cout << "m * n = "<< (m*n) << endl << endl;
cout << "m == n " << " is " << (m==n? "true": "false") << endl;
cout << "m != n " << " is " << (m!=n? "true": "false") << endl << endl;
cout << "m^2 = " << (m^2) << endl;
return 0;
}
能不能在大步骤的上方用//标一下步骤的目的挖,比如说//Matrix class definition, //overloaded operator+= delaration and definition. 刚学C++不大明白= = 3Q
追答代码太长这里没法贴了,我在ideone里面加了,你过去看吧
http://ideone.com/yDZnn
要是没法打开的话留个email我发给你