这是上次PPT所应该讲述的代码内容。现在放上来,大家就应该清楚PPT未完成的部分所想要描述的技术了。PS:代码中还是有些没用的东西。
template <typename LeftExp, typename Op, typename RightExp>
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
struct Expression
{
const LeftExp & left;
const RightExp & right;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
Expression(const LeftExp & _l, const RightExp & _r) : left(_l), right(_r)
{}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
double operator [] (int index) const
{
return Op::eval(left[index], right[index]);
}
};
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
struct EPLUS
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
static double eval(double a, double b)
{ return a+b;}
};
![](/Images/OutliningIndicators/None.gif)
class Matrix
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
private:
int M,N;
double * element;
public:
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
Matrix(int m, int n): M(m),N(n)
{
element = new double[M*N];
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
~Matrix()
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if (element)
{
delete []element;
element = 0;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int getM() const
{ return M;}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int getN() const
{ return N;}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int getSize() const
{return M*N;}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
double & operator ()(int i, int j) const
{ return element[i*N+j]; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
double operator [](int index) const
{return element[index]; }
template <typename Exp>
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
Matrix & operator = (Exp & exp)
{
int size = M*N;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for (int i=0;i<size;i++)
{
element[i] = exp[i];
}
return * this;
}
![](/Images/OutliningIndicators/InBlock.gif)
template <typename LeftExp, typename RightExp>
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
inline Expression<LeftExp,EPLUS, RightExp> operator + (const LeftExp & a, const RightExp & b)
{
return Expression<LeftExp, EPLUS, RightExp>(a, b);
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int main()
{
const int M=3, N=4;
Matrix a(M,N), b(M,N), c(M,N);
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for (int i=0;i<M;i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for (int j=0;j<N;j++)
{
a(i,j) = i+j;
b(i,j) = i*j;
c(i,j) = 0;
}
}
c = a + b;
return 0;
}