簡體   English   中英

在cpp中返回一對時出錯

[英]Error returning a pair in cpp

我有以下代碼:

 return new std::pair<BST<Data>::iterator(cursor), true>;

這會導致以下錯誤:

無法將'(operator new(4u),(,((int *))))'從'int *'轉換為'std :: pair,bool>'
“template struct std :: pair”的模板參數列表中參數1的類型/值不匹配

這可能是什么問題?

除了new (不要使用new除非你必須)並return ,為了構造一pair ,使用提到的make_pair()函數或調用這樣的構造函數: pair<T1, T2>(v1, v2) 您正在將類型( pair<T1, T2> )與init的類型實例( v1, v2 )混合起來。

你想回來的是什么? 一對值或實際上指向新對象的指針? 在函數聲明中查看返回類型以了解您的意圖可能很有用。

如果你想要返回一對,你最好使用:

template <class T1,class T2>
  pair<T1,T2> make_pair (T1 x, T2 y)
  {
    return ( pair<T1,T2>(x,y) );
  }

就是這樣的:

return  std::make_pair ( BST<Data>::iterator(cursor),  true);

或直接:

return ( pair<T1,T2>(x,y) );

就是這樣的:

return ( std::pair< BST<Data>::iterator , bool>( cursor, true) );

如果指向新創建的對象,如果你想要的話,使用:

return ( new std::pair< BST<Data>::iterator , bool>( cursor, true) );

現在:

這可能是什么問題?

看着:

template <class T1, class T2> struct pair
{
  typedef T1 first_type;
  typedef T2 second_type;

  T1 first;
  T2 second;
  pair() : first(T1()), second(T2()) {}
  pair(const T1& x, const T2& y) : first(x), second(y) {}
  template <class U, class V>
    pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
};

您正嘗試使用我們需要類型T1T2值來實例化模板。

暫無
暫無

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

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