簡體   English   中英

嵌套類中的編譯問題

[英]Compilation Issue in Nested classes

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.

我已按照成員的建議在頭文件中添加了所有模板定義

================================================== ==================================
Test.h ------- #include使用命名空間std;

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

您向前聲明了B類( class B; ),但沒有提供任何定義。 (顯然,您稍后會在A中聲明另一個class B ,但請注意, ::B (您在全局名稱空間中聲明的B )不是A::B (您在類中聲明的B

另外,它是private ,不是Private 而且,如果使用模板,請將所有方法定義都放在頭文件中,否則會出現很多錯誤。

另外, std::map<B*,int> mymap; 聲明一個全局變量,而不是類型,因此以后不能使用它,例如: mymap m_asc_map; 嘗試做一個“適當的” typedef :)

可能是因為您將模板定義放在* .cc文件中。 建議將所有模板定義放在* .h文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM