开发者

forward declaration and typename using new keyword

开发者 https://www.devze.com 2023-01-26 08:42 出处:网络
I\'m getting an error below in the class a declaring a new pointer of type b. Please help. #include <iostream>

I'm getting an error below in the class a declaring a new pointer of type b. Please help.

#include <iostream>

namespace B
{
    class b;
}
class a
{
    private:

    B::b* o开发者_JS百科bj_b;

    public:

    a(){}
    ~a(){}
    void create()
    {
        b* obj_b = new b;
    }
};
class b
{
    private:

        a *obj_a;

    public:
        b()
        {
            obj_a->create();
        }
        ~b(){}
};
int main()
{
    b obj;

    return 0;
}


b* obj_b = new b;

And there is your problem. You can declare a pointer to a B because pointers are all the same size, but you cannot construct one or take one by value without providing the class definition to the compiler. How would it possible know how to allocate memory for an unknown type?


There were many errors in your code. These are related to forward declaration, fully qualified name usage etc.

namespace B 
{ 
   class b; 
} 
class a 
{ 
private: 

   B::b* obj_b;            // change 1 (fully qualified name)

public: 
   void create();          // change 2 (can't use b's constructor now as B::b is not 
                           // yet defined)
   a(){} 
   ~a(){} 

}; 

class B::b                 // change 3 (fully qualified name)
{ 
private: 

   a *obj_a; 

public: 
   b() 
   { 
      obj_a->create(); 
   } 
   ~b(){} 
}; 

void a::create()             // definition of B::b's constructor visible now.    
{ 
   B::b* obj_b = new B::b;   // And here also use fully qualified name
} 

int main() 
{ 
   B::b obj; 

   return 0; 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号