#include <iostream.h>
class Matrix
{
friend istream& operator >> (istream& input,Matrix& d);
friend ostream& operator << (ostream& output,Matrix& d);
public:
int Mat[4];
Matrix() {
for(int i=0;i<=3;i++)
Mat[i]=0;
}
Matrix operator *(Matrix t);
};
istream& operator >> (istream& input,Matrix& d) {
for(int i=0;i<=3;i++)
input >> d.Mat[i];
return (input);
}
ostream& operator << (ostream& output,Matrix& d) {
for(int i=0;i<=1;i++) {
output << "|";
for(int j=0;j<=3;j++)
output << d.Mat[i];
output << "|" << endl;
}
return (output);
}
Matrix Matrix::operator *(Matrix t) {
int coun1=2,temp=0;
Matrix Maxout;
for(int i=0,j=1;i<=3;i+=2,j+=2,temp++,coun1=2)
for(int k=0;k<=1;k++,coun1++)
Maxout.Mat[temp]=t.Mat[i]*t.Mat[k]+t.Mat[j]*t.Mat[coun1];
return (t);
}
void main() {
Matrix M1,M2,M3;
cin >> M1;
cin >> M2;
M3=M1*M2;
cout << M3;
}
// 在C++中 可以通过重载使<< 和>> 支持插入和提取一个struct 结构体对象, 具体实现方式如下:
# include<iostream>
useing namespace std;
struct test
{
char a;//一个字节,但填充了3个字节
int b;//4字节
friend istream& operator >> (istream& input, test& St);
friend ostream& operator << (ostream& output, test& St);
} ;//sizeof(test) = 8
istream& operator >> (istream& input,test& St)
{
char cha[1];
input.read(cha,1);
memcpy(&St.a,cha,1);
char zero[3];
input.read(zero,3);
char chb[4];
input.read(chb,4);
memcpy(&St.b,chb,4);
return (input);
}
ostream& operator << (ostream& output,test& St)
{
char cha[1] ;
memcpy(cha,St.a,1);
output.write(cha,1);
char zero[3] = {0,0,0x00};
output.write(zero,3);
char chb[4] = {St.b & 0xff,St.b >> 8,St.b >> 16,St.b >>24};
output.write(chb,4);
return (output);
}
void main() {
test st1;
char buffer[8];
stringstream ssbuffer;
string sbuffer;
st1.a='x';
st1.b=123;
ssbuffer << st1; //把St1插入到流;
sbuffer = ssbuffer.str();
memcpy(buffer,sbuffer.c_str(),sbuffer.size()); //把St1 内容保存到数组buffer(做永久保存)
test st2;
ssbuffer.write(&buffer,8);//(需要的时候)把St1内容从数组插入到流
ssbuffer >> st2;// 把st1的内容直接提取给st2;
}