前向声明和命名空间的关系

问题描述

//a.hh

class B;
namespace test{
class A
{
public:
    A(B* b);
private:
    B* bb_;
};
}//end test

//a.cc
#include "a.hh"
#include "b.hh"

namespace test{
A::A(B* b) // 这里会报错
: bb_(b)
{
}
}// end test

//b.hh
namespace test{
class B
{
int some;
};
}//end test

报错原因是 cannot initialize a member subobject type B * with an lvalue of type test::B *

原因在于前向声明没有放到namespace test中去。
我们会默认为存在俩个类,一个是::B
一个是test::B

我们手动加上命名空间实际上是

//a.cc
#include "a.hh"
#include "b.hh"

namespace test{
A::A(test::B* b) // 这里会报错
: (::B)bb_(b)
{
}
}// end test

修改

就是在a.hh中,将前向声明B放到namespace test中去。

猜你喜欢

转载自blog.csdn.net/weixin_43468441/article/details/92115021