![](/img/trans.png)
[英]Error 5 error C2039: 'update' : is not a member of 'std::_Vector_iterator<_Myvec>'
[英]cannot convert parameter 1 from 'std::_Vector_iterator<_Myvec>' to '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
}
};
當我嘗試編譯它時,我收到錯誤:
無法將參數1從'std :: _ Vector_iterator <_Myvec>'轉換為'std :: _ Vector_iterator <_Myvec>'
所以基本上,我要問題 -
complex
結構在兩個類中定義。 const iterator
上聲明,所以它只是只讀? 我不確定 ... 這是因為A::complex
和B::complex
是不同的類型(具有相同的內容,但無關緊要)。 因此, vector<A::complex>
和vector<B::complex>
是不同的。 在A
和B
之外移動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();
}
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解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.