[英]Accessing data by using a vector of pointers inside a function from the same class C++
這是我的問題:我正在使用兩個不同的類A和B。類A包含一個指向類型B的對象的指針向量,我想在函數myfunc中使用該向量,該函數是A的成員。這是一個例子
class B {
public:
int x, y;
float z;
// other class members...
};
class A {
public:
// other class members...
vector <B*> myvect;
float myfunc() {
for(size_t i = 0; i < myvect.size(); ++i) cout << myvect[i] -> x << endl;
// rest of the code...
return (some float)
}
};
該程序無法編譯。 它返回一個錯誤,指出B是未定義的類型。 僅當我注釋掉cout語句時才編譯。 我在互聯網上搜索並嘗試了幾項操作,例如將i聲明為迭代器並取消引用該迭代器,但沒有任何效果。 任何想法這段代碼有什么問題嗎?
您可以在Ah
#include "Bh"
,或更正確的方法是,在A
的定義之前對class B
前向聲明,然后將實現移到標頭之外:
//B.h
class B
{
//...
};
//A.h
class B; //forward declaration
class A
{
//...
vector <B*> myvect; // <- correct syntax
float myfunc(); // only declaration
//...
};
//A.cpp
#include "A.h"
#include "B.h"
//...
float A::myfunc() { //implementation
for(size_t i = 0; i < myvect.size(); ++i) cout << myvect[i] -> x << endl;
// rest of the code...
return (some float)
}
//..
編譯錯誤源於以下事實:在cout
語句中,您正在取消引用 B的指針。為此,編譯器此時必須具有可用的類B的定義。
換句話說,像這樣的代碼
pointerToB->x
僅在該點之前包含#include "Bh"
有效。
因此,您可以在Ah
,或者為避免這種額外的耦合(並避免使用較大的頭文件),您可能希望將這樣的帶有指針引用的片段移入A.cpp
並在Ah
向前聲明類B,就像陸前所建議的 。
我會先嘗試添加括號:
cout << myvect[i] -> x << endl;
對此:
cout << ((myvect[i]) -> x) << endl;
我給它一個很好的機會,就是這樣簡單,並且cout試圖在箭頭運算符之前首先“獲取” B *對象。 如果不是,請發布編譯器錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.