質問

typedef int abc;

class Some{
   public:
      abc foo(){...}
      typedef double abc;
};

In the code above, I get it that I get an error:

error: changes meaning of 'abc' from 'typedef int abc'

because in the book c++ primer,fifth edtion, it says:

Class definitions are processed in two phases:

1.First, the member declarations are compiled.

2.Function bodies are compiled only after the entire class has been seen.

But in the code here:

typedef int abc;

class Some{
     public:
        int foo(abc){...}
        typedef double abc;
};

I set abc in the parameter list. But I didn't get that kind of error and the compiler works perfectly fine. why the latter code won't get me any error similar to the former?

役に立ちましたか?

解決

I don't think there is any reason. This error does not require a diagnostic (according to Standard C++), so the behavior is effectively undefined when you have this error in your code.

Your compiler just hasn't checked the parameter list for this error but may well have done it.

他のヒント

You need to qualify it, Some::abc:

typedef int abc;

class Some{
   public:
      Some::abc foo(){...}
      typedef double abc;
};

The reason that the first example gives an error is that name lookup does not take into account the return type. But when the actual function body is being generated in the expression where it is being called, the compiler will use Some::abc and find a discrepancy.

typedef int abc;

class Some{
   public:
      abc foo() { return abc(); }  // during lookup/resolution, "abc" is known to be int, return type is not considered
      typedef double abc;
};

int main() 
{ 
    Some s; 
    int x = s.foo(); // kaboom, return type is double.
}

In your second example, the type redefinition is inconsequential because during name lookup, abc is known to be an int, because the definition of the inner typedef has not yet been seen. There are no consequences during the instanation of the function at the call site, because the return type is also int. There is simply no mismatch.

typedef int abc;

class Some{
   public:
      int foo(abc) { return int(); }  // during lookup/resolution, "abc" is known to be int
      typedef double abc;             // this will not have been seen yet in the previous line
};

int main() 
{ 
    Some s; 
    int x = 0;
    s.foo(x); // OK, x is of type int
}

In MinGW, if return type of a member function appears as a alias type defined by typedef declaration. It is not allowed to change its meaning. The name lookup rule you ask for is still valid as usual introduced in the Lippman's C++ Primer at page 447 -- name lookup for class member declarations.

  1. The declaration of the class members that appear before the use of the name are considered.
  2. If the lookup in step 1 is not successful, the declarations that appear in the scope in which the class is defined, and that appear before the class definition itself, are considered.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top