草庐IT

C++ typedef 和返回类型 : how to get the compiler to recognize the return type created with typedef?

coder 2023-11-14 原文

#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;
}

在这一行中,myInt 未被编译器识别为“int”:

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

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

最佳答案

typedef 创建同义词,而不是新类型,因此 myIntint 已经相同。问题是作用域 — 在全局作用域中没有 myInt,您必须在类之外使用 A::myInt

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

关于C++ typedef 和返回类型 : how to get the compiler to recognize the return type created with typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10251980/

有关C++ typedef 和返回类型 : how to get the compiler to recognize the return type created with typedef?的更多相关文章

随机推荐