繁体   English   中英

使用同一类C ++中的函数内部的指针向量访问数据

[英]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.

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