使用new关键字转发声明和typename

时间:2010-11-19 03:47:55

标签: c++ namespaces forward-declaration fully-qualified-naming

我在类中声明了一个类型为b的新指针时出现错误。请帮忙。

#include <iostream>

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

    B::b* obj_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;
}

2 个答案:

答案 0 :(得分:6)

b* obj_b = new b;

还有你的问题。您可以声明指向B的指针,因为指针的大小都相同,但是在不向编译器提供类定义的情况下,您不能构造一个或按值取一个。怎么可能知道如何为未知类型分配内存?

答案 1 :(得分:1)

您的代码中存在许多错误。这些与前向声明,完全限定名称使用等有关。

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