C++ typedef和return类型:如何让编译器识别用typedef创建的返回类型?

use*_*343 9 c++ typedef

#include <iostream>
using namespace std;

class A {
    typedef int myInt;
    int k;
public:
    A(int i) : k(i) {}
    myInt getK();
};

myInt A::getK() { return k; }

int main (int argc, char * const argv[]) {
    A a(5);
    cout << a.getK() << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器将myInt识别为此行中的"int":

myInt A::getK() { return k; }
Run Code Online (Sandbox Code Playgroud)

如何让编译器将myInt识别为int?

Cat*_*lus 22

typedef创建同义词,而不是新类型,因此myInt并且int已经相同.问题是范围 - myInt在全球范围内没有,你必须A::myInt在课外使用.

A::myInt A::getK() { return k; }
Run Code Online (Sandbox Code Playgroud)