代码贴上,需要的自己看吧。废话就不多说了,差别在代码里,关于学术型的语言大家还是看一下技术解析贴把,我就不做赘述了。这里主要是为大家提供代码的区别 // 这里才是 工厂函数的精髓 #include <iostream> #include <string> using namespace std; class Operation { private: double _numberA; double _numberB; public: //Operation(){}; double getNumberA(){ return _numberA; } void setNumberA(int value){ _numberA = value; } double getNumberB(){ return _numberB; } void setNumberB(int value){ _numberB = value; } virtual double getResult(){ double result=0; return result; } }; class OperationAdd:public Operation{ private: public: double getResult(){ double result=0; result = getNumberA()+getNumberB(); return result; } }; class OperationSub:public Operation{ private: public: double getResult(){ double result=0; result = getNumberA()-getNumberB(); return result; } }; class Factory:public Operation { public: // 因为需要返回一个算法 Operation* createFactory(string str){ Operation* ope; char* a = new char[100]; // 为什么这里写成 new char() 下面ope就不能初始化?,有没有哪位知道的回一下哦,谢了 strcpy(a, str.c_str()); cout<<"size of a = "<<sizeof(a)<<endl; //?? 为什么是8 不应该是4 么,mac下是8,windows看情况 cout<<"lenth a = "<<strlen(a)<<endl; cout<<"a[0] ="<<a[0]<<endl if="" sizeof="" a="">0){ switch (a[0]) { case '+': delete a; ope = new OperationAdd(); break; case '-': ope = new OperationSub(); break; default: break; } } return ope; } }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; Operation* ope = new Operation(); Factory* fac = new Factory(); string str; str = "+++++++++++++++++++++++++++++++++++++++++++"; ope = fac->createFactory(str); ope->setNumberA(6); ope->setNumberB(5); cout<<ope->getResult()<<endl; delete fac; delete ope; return 0; } </ope-></endl></string></iostream>