简体   繁体   中英

Accessing data by using a vector of pointers inside a function from the same class C++

here is my problem: I'm working with two different classes A and B. Class A contains a vector of pointers to objects of type B and I want to use this vector in a function myfunc, which is a member of A. Here is an example

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)

}

};

The program does not compile. It returns an error saying that B is undefined type. It only compiles if I comment out the cout statement. I searched the internet and tried several things, like declaring i as an iterator and dereferencing the iterator, but nothing worked. Any ideas what's wrong with this code?

You can #include "Bh" inside Ah or, the more correct way, have a forward declaration for class B before the definition of A and move the implementation outside of the header:

//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)
}
//..

The compilation error stems from the fact that in your cout statement you are dereferencing the pointer to B. And to do that, the compiler must have a definition of class B available at this point.

In other words, the code like this

pointerToB->x

is valid only if you have #include "Bh" prior to that point.

So, you may either do it in Ah , or, to avoid this extra coupling (and also to avoid large header files), you may want to move such pieces with pointer dereferencing into A.cpp and forward-declare class B in Ah , just as Luchian suggests .

I'd try adding brackets first:

cout << myvect[i] -> x << endl;

to this:

cout << ((myvect[i]) -> x) << endl;

I'll put it at good odds that it's just something simple like that, and that cout is trying to "take" the B* object first, prior to the arrow operator. If that's not it, please post the compiler error messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM