cómo hacer #define macro para hacer #define "myInt x" "int * x = new int [5]"

Puedo hacer lo siguiente:

#define myInt(x) int* x = new int[5]

...

myInt(dog);

dog[1] = 3;
dog[2] = 5;

Pero quiero algo como:

#define myInt x  int* x = new int[5]

entonces puedo hacer

myInt dog;

dog[1] = 3;
dog[2] = 5;

What is the proper way to set this up to remove the the function setup??

I was trying to understand how Visual C++ 2010 got away from using pointers in declaring a class... cMy *my = new cMy(); --> cMy my;

preguntado el 31 de enero de 12 a las 08:01

You don't. There's no reason for such a construct. -

I don't think you can do that. You need to pass the arguments to an macro expansion in brackets. Also I would not recommend using macro expansion for something like that - this will probably lead to memory leaks and obscure code. -

Por qué no std::array<int,5> x;? -

#define macros can't be proper. Exceptions arise only a few times in your whole career. -

cMy my; crea un cMy on the stack, whereas new cMy allocates one on the heap. This is standard C++, not specific to Visual C++. -

3 Respuestas

You can't do this with a macro. You could do this:

typedef int myInt[5];

myInt dog;
dog[1] = 3;
dog[2] = 5;

But that means that dog es una matriz, no un puntero.

I'm not sure whether hiding an array type behind a typedef is a good idea, though.

Respondido el 31 de enero de 12 a las 12:01

"I'm not sure whether hiding an array type behind a typedef is a good idea, though" - I think experience with va_list proves that it isn't. The reason it's a bad idea is that if someone uses myInt as a function parameter then they pretty much need to know whether or not it's an array type, because if it is then weird stuff happens (their function takes a pointer and loses the size information). Since they have to know that really it's an array, not just any old type, you're losing a lot of the benefit of a type alias since you only partly hide the underlying type. - Steve Jessop

Depending on what you want to do, you could also crear una clase y la overload the subscript ([ ]) operador, por ejemplo:

class myInt
{
private:
   int m_List[5];

public:
   int& operator[] (const int nIndex)
   {
     return m_List[nIndex];
   }
};

Then you could also write:

myInt dog;
dog[1] = 3;
dog[2] = 5;

Respondido el 31 de enero de 12 a las 12:01

You can't. Macros always use parentheses for their parameters. What you are defining with your:

#define myInt x  int* x = new int[5]

es un reemplazo de myInt a x int* x = new int[5], and that's hardly what you want.

Stick with the first variant.

Respondido el 31 de enero de 12 a las 12:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.