c++匿名类—指针

1 摘自网上

2代码实例

#include <iostream>
#include <list>
#include <iterator>
#include <cmath>

using namespace std;

class Term
{
    public:
        Term(int c,int e):coef(c),exp(e){

        }
        float TermValue();
        int GetCoef()
        {
            return coef;
        }
        int GetExp()
        {
            return exp;
        }
        static void SetX(float x_t)
        {
            x=x_t;
        }
        int GetX()
        {
            return x;
        }
    private:
        int coef;
        int exp;
        static float x;
};

float Term::x=1.0;

float Term::TermValue()
{
    return coef*pow(x,exp);
}

int main()
{
    list<Term> poly;
    list<Term>::iterator begin,end;
    int i;
    float  result=0;
//此处使用了c++中匿名内部类,区分java,c++中new后是一个指针类型
    for(i=1;i<5;i++) poly.push_back(Term(i,i));
    begin=poly.begin();
    end=poly.end();
    begin->SetX(2);
    do
    {
        result+=begin->TermValue();
        begin++;
    }while(begin!=end);
    cout<<result<<endl;
}

 

输出结果:98 正确

c++中的匿名内部类不需要new,new后是一个指针类型;java中的匿名内部类是一个引用类型。 分清楚。

posted @ 2015-12-19 22:00  小德cyj  阅读(3170)  评论(0编辑  收藏  举报