Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting variables between classes

Tags:

c++

class

I have this structure of class and I don't know, why I got error. It's very hard too search a problem, because of error output.

error: cannot convert 'A::C*' to 'C*' in assignment: two = this;

How can I fix this error?

class B;
class C;

class A{
 class B{
   public:
   B* one
   C* two;
   And some methods....
   ...
 };
 class C : public B{
   public:
   int f;
   C(){
    two = this; //here is error
   }
 };
};
like image 493
Nejc Galof Avatar asked Sep 27 '26 16:09

Nejc Galof


1 Answers

Your example declares 5 different classes (fully qualified, in order): ::B, ::C; ::A, ::A::B and ::A::C, because in your code

class B;
class C;

declares ::B and ::C in the global namespace, which you probably didn't intend to. This lead the compiler to believe that the unqualified C in the C* two; field in ::A::B refers to ::C instead of ::A::C.

Instead declare these classes inside class A {} like this:

class A{
 class B; // declares ::A::B
 class C; // declares ::A::C
 class B{
   public:
   B* one
   C* two; // ::A::C*
   And some methods....
   ...
 };
 class C : public B{
   public:
   int f;
   C(){
    two = this; // should work now
   }
 };
};

In the above the compiler now knows that by C* you mean ::A::C* because when searching for a matching type for C it encounters the declaration of class C; in the inner scope of class A {};. However, it doesn't "see" the actual definition of ::A::C declared below.

Detailed rules for unqualified name lookup can be found in section §3.4.1 of the C++ standard (draft version).

like image 102
jotik Avatar answered Sep 30 '26 05:09

jotik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!