Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typedef and return types: how to get the compiler to recognize the return type created with typedef?

Tags:

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

myInt is not recognized by the compiler as an 'int' in this line:

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

How can I get the compiler to recognize myInt as int?

like image 394
user52343 Avatar asked Apr 20 '12 18:04

user52343


People also ask

Does typedef create a new type?

Syntax. Note that a typedef declaration does not create types. It creates synonyms for existing types, or names for types that could be specified in other ways.

How do Typedefs work in C++?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

Are Typedefs scoped?

A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.


1 Answers

typedef creates synonyms, not new types, so myInt and int are already the same. The problem is scope — there is no myInt in a global scope, you have to use A::myInt outside of the class.

A::myInt A::getK() { return k; }
like image 188
Cat Plus Plus Avatar answered Nov 15 '22 19:11

Cat Plus Plus