嵌套类中的编译问题

Compilation Issue in Nested classes

本文关键字:编译 问题 嵌套      更新时间:2023-10-16
I am very new to the C++ and i am facing an issue in compiling the following code.
    Some one please help me out .Thanks in Advance.

我已经按照成员的建议在头文件中添加了所有模板定义

===============================================================================================================================================================================================================================================================

==
测试.h ------- #include 使用命名空间标准;

class B;
typedef std::map<B*,int> mymap;
template <class T>
class A
{
  private:
     class B
     {
       public:
       B(T);
       ~B();
       private:
       //some data members
     };
 public:
 A();
 ~A();
 bool add(T);
 bool sort();
 private:
 mymap m_asc_map;
 B* b;
};
template <class T>
A<T>::B::B(T)
{
}
template <class T>
A<T>::B::~B()
{
}
template <class T>
A<T>::A()
{
}
template <class T>
A<T>::~A()
{
}
template <class T>
bool A<T>:: add(T x)
{
  b = new B(x);
  return true;
}
template <class T>
bool A<T>:: sort()
{
   m_asc_map.insert(std::make_pair(b,1));
  return true;
}
Test.cc
-------
#include "Test.h"
int main()
{
  A<int> a;
  a.add(10);
  a.sort();
  return 0;
}
=====================================================================================
I am getting the following error
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h: In constructor ‘std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = A<int>::B*, _U2 = int, _T1 = B* const, _T2 = int]’:
Test.h:56:   instantiated from ‘bool A<T>::sort() [with T = int]’
Test.cc:7:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h:90: error: cannot convert ‘A<int>::B* const’ to ‘B* const’ in initialization

也许是因为您将模板定义放在 *.cc 文件中。建议将所有模板定义放在 *.h 文件中。

你转发声明类 B ( class B; (,但没有提供它的定义。(显然,您稍后在 A 中声明了另一个class B,但请注意,::B(您在全局命名空间中声明的B(不是A::B(您在类中声明的B(

另外,它是private,而不是Private。如果您使用模板,请将所有方法定义放在头文件中,否则您将获得更多错误。

此外,std::map<B*,int> mymap;声明的是全局变量,而不是类型,因此您以后不能像以下那样使用它:mymap m_asc_map; 。尝试做一个"适当的"typedef :)