cpp 多态的计算器例子。
#include<iostream>using namespace std;
#include<string>
class jsj//普通类
{
public:
int a, b;
void get(int a,int b)
{
this->a = a;
this->b = b;
}
int jg(string fh)
{
if (fh == "+")
{
return a + b;
}
else if (fh == "-")
{
return a - b;
}
else if (fh == "*")
{
return a * b;
}
else if (fh == "/")
{
return a / b;
}
}
};
void test01()
{
jsj j1;
j1.get(10, 20);
cout << "+法" << j1.jg("+") << "-法" << j1.jg("-") << "*法" << j1.jg("*") << "/法" << j1.jg("/") <<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
普通类不方便后面维护
#include<iostream>
using namespace std;
#include<string>
class absjsj//多态实现计算机
{
public:
virtual int js()
{
return 0;
}
int a, b;
};
class add:public absjsj
{
public:
int js()
{
return a + b;
}
};
class sub :public absjsj
{
public:
int js()
{
return a - b;
}
};
class ride :public absjsj
{
public:
int js()
{
return a * b;
}
};
class exc :public absjsj
{
public:
int js()
{
return a / b;
}
};
void test01()
{
absjsj* abs = new add;
abs->a = 10;
abs->b = 5;
cout <<"加法"<< abs->js() << endl;
delete abs;
abs = new sub;
abs->a = 10;
abs->b = 3;
cout << "减法" << abs->js() << endl;
delete abs;
abs = new ride;
abs->a = 9;
abs->b = 8;
cout << "乘法" << abs->js() << endl;
delete abs;
abs = new exc;
abs->a = 8;
abs->b = 4;
cout << "除法" << abs->js() << endl;
delete abs;
}
int main()
{
test01();
system("pause");
return 0;
}
多态更方便实现后期的维护。 感谢楼主辛苦分享 感谢分享,这就去实现一下 这个是继承和多态 再加上模版,把处理的数据类型也抽象出来 好棒,用到了virtual函数 纯虚函数的实现案例,冲咖啡
#include<iostream>
using namespace std;
class absreactdrinking//纯虚函数的实现
{
public:
//煮水
virtual void boil() = 0;
//冲泡
virtual void brew() = 0;
//倒入杯中
virtual void pourincup() = 0;
//加辅料
virtual void putsomething() = 0;
void makedrink()
{
boil();
brew();
pourincup();
putsomething();
}
};
class coffee :public absreactdrinking
{
public:
//煮水
virtual void boil()
{
cout<<"煮神水"<<endl;
}
//冲泡
virtual void brew()
{
cout << "冲咖啡" << endl;
}
//倒入杯中
virtual void pourincup()
{
cout<<"倒杯"<<endl;
}
//加辅料
virtual void putsomething()
{
cout << "加糖" << endl;
}
};
void dowork(absreactdrinking* abs)
{
abs->makedrink();
delete abs;
}
void test()
{
//创建咖啡
dowork(new coffee);
}
int main()
{
test();
system("pause");
return 0;
} 谢大佬分享 谢谢楼主分享。
THANK YOU VERY MUCH.
页:
[1]
2