在VC ++中通过宏定义变量 [英] define variable by macro in VC++

查看:220
本文介绍了在VC ++中通过宏定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于定义变量的宏为:

The macro to define a variable is:

//Define macro ============
#define mcr_defineVar(t,v)  t v;
//Use======================
      mcr_defineVar(int,a); //same as int a;
      a = 10; // =>a = 10;



但是我想做一些陈述:



But I want to do some statements:

mcr_defineVar("int",a);







OR

mcr_defineVar("int","a");



预期为:int a;

我不知道要这么做.

你能帮我吗?


谢谢!
TCBinh-VietNam



Expected is: int a;

I don''t know to do it.

Can you help me, please?


Thank you!
TCBinh - VietNam

推荐答案

您的代码在Visual C ++ 6中可以正常编译(至少突出显示的代码可以).您将不需要在第二个示例中使用双引号.
Your code compiles fine in Visual C++ 6 (at least the highlighted code does). You won''t need the double quotes that you use in your second example.


使用以下命令调用宏时:

mcr_defineVar("int",a);

宏的第一个参数是5个字符:"int"

此参数逐字替换为宏文本(对于t).没有办法避免这种情况.您不能摆脱双引号.

但是,真正的问题是您为什么要这样做?正如前面的答案所说,您不需要双引号.我还要说的是,使用宏定义变量会使任何阅读代码的人感到困惑.

如果您可以告诉我们您要实现的目标,我们可以告诉您正确的方法.
When you invoke the macro using:

mcr_defineVar("int",a);

the first parameter to the macros is the 5 characters: "int"

This parameter is substituted into the macro text (for t) verbatim. There is no way to avoid that. You can''t get rid of the double-quotes.

However, the real question is why do you want to do this? As the previous answer says you don''t need the double-quotes. I would also say that using a macro to define a variable is very confusing to anyone reading the code.

If you could tell us what you are trying to achieve, we could tell you the right way to do it.


不确定这些方法是否有帮助

Not sure if these will help

// Helper macro BOOST_JOIN:
// The following piece of macro magic joins the two
// arguments together, even when one of the arguments is
// itself a macro (see 16.3.1 in C++ standard).  The key
// is that macro expansion of macro arguments does not
// occur in BOOST_DO_JOIN2 but does in BOOST_DO_JOIN.
//
#define BOOST_JOIN( X, Y ) BOOST_DO_JOIN( X, Y )
#define BOOST_DO_JOIN( X, Y ) BOOST_DO_JOIN2(X,Y)
#define BOOST_DO_JOIN2( X, Y ) X##Y


这篇关于在VC ++中通过宏定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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