2015-06-11 81 views
3

我有一個問題,它有點難以描述它,所以請容易對我。不能將參數1從'std :: _ Vector_iterator <_Myvec>'轉換爲'std :: _ Vector_iterator <_Myvec>'

我有兩個類,A和B,A級有一個私人成員 - 矢量:

class A 
{ 
private: 
    struct complex 
    { 
     int x; 
     vector<int> y; 
    }; 

    vector<complex> m_resultVector; // <---- the private member 

public: 
    void getPointerToVector(vector<complex>::iterator it) 
    { 
     it = m_resultVector.begin(); 
    } 
}; 

我需要從B類可以訪問(只讀),這m_resultVector;,我可以寫get函數,但m_resultVector是非常長的矢量,我不想將整個矢量複製到新的矢量,我想發送它的指針。我也需要B類的重要部分 - 不能改變的m_resultVector

class B 
{ 
    struct complex 
    { 
     int x; 
     vector<int> y; 
    }; 

    void functionOf_B() 
    { 
     A class_A; 
     vector<complex>::iterator p_resultVector; 

     class_A.getPointerToVector(p_resultVector); // <------ compilation error here 

     // some reading from the content of p_resultVector 
    } 
}; 

當我嘗試編譯它的內容,我得到的錯誤:

cannot convert parameter 1 from 'std::_Vector_iterator<_Myvec>' to 'std::_Vector_iterator<_Myvec>'

所以基本上,我有問題 -

  1. 爲什麼我得到這個錯誤?這兩個類中都定義了complex結構。
  2. 我需要在B類的const iterator上聲明哪裏以及如何聲明,因此它只能被讀取?我不確定...
+2

'A :: complex'和'B :: complex'是不同的類型。 –

+0

這是行不通的,因爲B中複雜結構的向量與A中複雜結構的不同,您試圖在2個類之間進行轉換。 – Spanky

+0

我明白了..所以我怎樣才能返回一個const指針,該矢量? – user1673206

回答

5

這是因爲A::complexB::complex是不同的類型(具有相同的內容,但沒關係)。所以vector<A::complex>vector<B::complex>是不同的。在AB之外移動struct complex的定義。

此外,您的代碼中還存在更多問題。 A::getPointerToVector不做任何事情,因爲它將輸入向量迭代器複製到臨時對象,爲其分配一個值,並在從該函數返回後,所有內容都將丟失。使用這種方法,您必須通過vector<complex>::iterator作爲參考(因此vector<complex>::iterator&)。

我寧願寫A的方法是這樣

const vector<complex>& get_vector() const 
{ 
    return m_resultVector; 
} 

我這樣,你就可以鬥這一點。

void foo() 
{ 
    A class_A; 
    // do something with A 
    const vector<complex>& p_result = class_A.get_vector(); 

    // now you are holding whole vector and you can call methods 
    // defined as const (which does not modify that vector) 
    p_result.begin(); 
    p_result.at(0); 
    p_result.end(); 
} 
0

Zereges解決方案看起來不錯。但我明白你不想返回向量。除了下面的內容,我無法提出任何解決方案。

在A類:

void getPointerToVector(int position, int &var,vector<int>& o_Vec) 
{ 

    vector<complex>::iterator itr; 
    complex c; 
    c = m_resultVector.at(position); 
    var = c.x; 
    o_Vec = c.y; 

} 

在B類:

void functionOf_B() 
{ 

    A class_A; 
    int aVar; 
    std::vector<int> vec; 
    class_A.getPointerToVector(2, aVar, vec); 


     // some reading from the content of p_resultVector 

} 

我不知道如何有效的和複雜的,這是。我建議最好使用Zereges解決方案

相關問題