不能在C ++中使用宏定义类 [英] Can't use macro define class in C++

查看:131
本文介绍了不能在C ++中使用宏定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成很多子类,只有很少的区别,所以我想使用宏来简化我的工作。宏定义如下:

I want to generate many sub-class which only has little difference, so I want to use macro to simplify my job. The macro define below:

#define DECLARE_SUB_CLASS(sub_class_name, base_class_name, value1) \
class sub_class_name:base_class_name \
{ \
public: \
    virtual int initialize(const void *); \
    virtual int run(const void *); \
    virtual void reset(); \
    virtual int output(const char*); \
    virtual void terminate(); \
private: \
    static const char m_szValue=#value1; \
};

我这样使用:

DECLARE_SUB_CLASS(RTCount13, RTCountBase, 13);

当我用VC2005编译时,它说

when I compiling with VC2005, it say

error C2065: 'RTCount13' : undeclared identifier

问题?

推荐答案

使用gcc -E(或其他预处理器类似的)

Use gcc -E (or similar for other preprocessor)

gcc -E prepro.cxx

gcc -E prepro.cxx

# 1 "prepro.cxx"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "prepro.cxx"
# 17 "prepro.cxx"
class RTCount13:RTCountBase { 
  public: 
  virtual int initialize(const void *); 
  virtual int run(const void *); 
  virtual void reset(); 
  virtual int output(const char*); 
  virtual void terminate(); 
  private: 
  static const char m_szValue="13"; 
};;

您尝试将13一个炭。

顺便说一句,你也可以使用一个模板而不是一个宏来做你的宏完全相同的事情(即声明但不定义方法)。下面是一个具有单独方法定义的完整(修剪)示例。

By the way you could also use a template instead of a macro to do the exact same thing your macro did (namely to declare but not define the methods). Here's a complete (trimmed down) example with separate method definitions.

#include <iostream>
class RTCountBase {};

template <class base_class_name, int v>
class RTCount: base_class_name { 
  public: 
   virtual int output(); 
   virtual void terminate(); 
  private: 
   static const int m_szValue=v; 
};

template <class base_class_name, int v>
int RTCount<base_class_name,v>::output(){ return m_szValue; }

template <class base_class_name, int v>
void RTCount<base_class_name,v>::terminate(){ std::cout <<" term "<<std::endl; }

typedef RTCount<RTCountBase,13> RTCount13; // typedef instead of macro
typedef RTCount<RTCountBase,14> RTCount14;

int main(){
   RTCount13 myc13;
   RTCount14 myc14;
   std::cout << "my13: "<<myc13.output()<<std::endl;
   std::cout << "my14: "<<myc14.output()<<std::endl;
   return 0;
}

这篇关于不能在C ++中使用宏定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆