读书人

为何编译不过去

发布时间: 2012-09-10 11:02:32 作者: rapoo

为什么编译不过去
从网上复制了一段代码。可是在VC++上编译不过去。大家能帮我看看什么原因吗?想了很久,也没想出来

C/C++ code
 #include   <string>   #include   <map>   #include   <iostream>using namespace std;typedef void* (*CreateFuntion)(void);class ClassFactory{public: static void* GetClassByName(std::string name) {  std::map<std::string,CreateFuntion>::const_iterator find;  find=m_clsMap.find(name);  if(find==m_clsMap.end())  {   return NULL;  }  else  {   return find->second();  } } static void RegistClass(std::string name,CreateFuntion method) {  m_clsMap.insert(std::make_pair(name,method)); }private: static std::map<std::string,CreateFuntion> m_clsMap;};std::map<std::string,CreateFuntion>   ClassFactory::m_clsMap; class RegistyClass{public: RegistyClass(std::string name,CreateFuntion method) {  ClassFactory::RegistClass(name,method); }};template<class T,const char name[]>class Register{public: Register() {  //这个一定要加,因为编译器不保证程序开始时就初始化变量rc  const RegistyClass tmp=rc; } static void* CreateInstance() {  return new T; }public: static const RegistyClass rc;};template<class T,const char name[]>const RegistyClass Register<T,name>::rc(name,Register<T,name>::CreateInstance);#define DEFINE_CLASS(class_name) /char NameArray[]=#class_name;/class class_name:public Register<class_name,NameArray>#define DEFINE_CLASS_EX(class_name,father_class) /char NameArray[]=#class_name;/class class_name:public Register<class_name,NameArray>,public father_classDEFINE_CLASS(CG){public: void Display() {  printf("fff"); }};int main(int argc, char* argv[]){  CG* tmp=(CG*)ClassFactory::GetClassByName("CG"); tmp->Display(); return 0;}

C# code
:\ReflectionTest\main.cpp(58) : error C2061: syntax error : identifier 'name'F:\ReflectionTest\main.cpp(58) : error C2063: 'rc' : not a functionF:\ReflectionTest\main.cpp(58) : error C2373: 'rc' : redefinition; different type modifiers        F:\ReflectionTest\main.cpp(55) : see declaration of 'rc'F:\ReflectionTest\main.cpp(60) : error C2014: preprocessor command must start as first nonwhite spaceF:\ReflectionTest\main.cpp(64) : error C2014: preprocessor command must start as first nonwhite spaceF:\ReflectionTest\main.cpp(73) : error C2226: syntax error : unexpected type 'class_name'F:\ReflectionTest\main.cpp(74) : error C2061: syntax error : identifier '_TCHAR'F:\ReflectionTest\main.cpp(77) : error C2065: 'CG' : undeclared identifierF:\ReflectionTest\main.cpp(77) : error C2065: 'tmp' : undeclared identifierF:\ReflectionTest\main.cpp(77) : error C2059: syntax error : ')'F:\ReflectionTest\main.cpp(78) : error C2227: left of '->Display' must point to class/struct/unionError executing cl.exe.main.obj - 11 error(s), 11 warning(s)

还有问一下,#define 预处理中的井号作为连接串的时候在 linux的编译器上 不起作用吗?

[解决办法]
#define DEFINE_CLASS(class_name) /
char NameArray[]=#class_name;/
这里的 / 应该全部是续行符才对

读书人网 >C++

热点推荐