首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++ 多态二

2012-09-08 
c++ 多态2void printStr2 (std::pairstd::string,float score1) //打印字符串{cout score1.first:

c++ 多态2
void printStr2 (std::pair<std::string,float> score1) //打印字符串
{
cout << score1.first<<":"<<score1.second <<"\t";
}
//   定义两个重载函数  
int my_add(int a,int b)  
{  
return a+b;  
}  
int my_add(int a,std::string b)  
{  
return  a + atoi(b.c_str());  
}  

//宏多态
#define ADD(a,b){a+b} ;
#define ADD2(a,b) (a) +(b) ;

void run_vehicle(const extendsNamespace::Vehicle* vehicle)
{
    vehicle->run();////   根据vehicle的具体类型调用对应的run()
}

//   通过引用而run任何vehicle
template <typename Vehicle1> //Vehicle1不是一个类,是一个模板
void run_vehicle1(const Vehicle1& vehicle1)
{
     vehicle1.run();
}

//   run异质vehicles集合  
void  run_vehicles(const std::vector <extendsNamespace::Vehicle*>&  vehicles)  
{  
for (unsigned int i=0;i<vehicles.size();++i)  
{  
vehicles[i]->run();   //   根据具体vehicle的类型调用对应的run()  
}  
}  

//#endif
using namespace extendsNamespace;
int _tmain(int argc, _TCHAR* argv[])
{
cout<<">>>>>>>>>>extends"<<endl;
    //typedef 定义的结构变量
/*stu1 stu1obj;
stu1obj.name = "张三typedef";
stu1obj.age = 12;

stu2 stu2obj;
stu2obj.name = "张三2typedef";
stu2obj.age = 22;

//直接操作结构变量
    stu21obj.name = "张三";
stu21obj.pwd = "123";
stu21obj.socres.push_back(std::make_pair("语文",12.2f));
//stu21obj.socres.push_back(std::pair("数学",65));//出错
//std::pair< int, std::string > author(2,"aaaaaaaaa");
    std::pair<std::string,float> score1("数学",65.5f);
stu21obj.socres.push_back(score1);


cout<<"姓名\t"<<"密码\t"<<"成绩"<<endl;
cout<<stu21obj.name<<"\t"<<stu21obj.pwd<<"\t";

for_each(stu21obj.socres.begin(),stu21obj.socres.end(),printStr2);


stu22obj.name = "张三222";
stu22obj.pwd = "123222";
cout<<"\r\n"<<stu22obj.name<<"\t"<<stu22obj.pwd<<"\t";*/

/*//函数多态(方法重载)
int i = my_add(1,2);   //   两个整数相加  
int s = my_add(1," 2 ");   //   一个整数和一个字符串相加,前后有空格也是可以atoi的  
std::cout<<"i="<<i<<endl;  
std::cout<<"s="<<s<<endl;*/
   
/*//宏多态
    int i1(1),i2(2);
std::string s1("Hello,  ");
std::string s2("world!");
   
int i = ADD(i1,i2);
    std::cout<<"i="<<i<<endl;
i = ADD2(i1,i2);
    std::cout<<"i2="<<i<<endl;
    std::string s;
//s = ADD(s1,s2);//不行
s = ADD2(s1,s2);
cout<<s<<endl;*/

/*//动态多态
Car car;
Airplane airplane;
    run_vehicle(&car);
run_vehicle(&airplane);
*/
/*cout<<" 异质vehicles集合"<<endl;
std::vector<Vehicle*> v; //   异质vehicles集合
v.push_back(&car);
v.push_back(&airplane);
run_vehicles(v);//   run不同类型的vehicles  */

//静态多态
Car1 car1;
Airplane1 airplane1;
run_vehicle1(car1);   //   调用Car::run()  
run_vehicle1(car1);   //   调用Airplane::run()

getchar();
//system("pause");
return 0;
}

热点排行