#define myptr int*有什么问题?

Ani*_*hag 2 c++ macros

这是一小段代码:

#include <iostream>
using namespace std;

#define myptr int *

int main(){
    myptr p,q;
    int c;
    p = &c;
    q = &c;
    c = 2;
    cout<<c<<endl;
    cout<<*p<<endl;
    cout<<*q<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

p有类型int*q有型int.为什么会这样?

Yu *_*Hao 7

宏替换后,myptr p,q;变为

int *p,q;
Run Code Online (Sandbox Code Playgroud)

认为是的类型q是一个常见的错误int*,但事实上它是int.

你需要的是typedef:

typedef int* myptr;
Run Code Online (Sandbox Code Playgroud)


Mar*_*som 5

*结合到变量,而不是类型.您需要为该行上的每个声明重复它.

typedef会以您期望的方式工作:

typedef int * myptr;
Run Code Online (Sandbox Code Playgroud)