在C++中从不同的类检索数据
Retrieving data from different classes in C++
我在使用不同类访问方法和参数时遇到了问题,我以前用Java编写代码,所以使用其他作用域的函数没有问题。
class Ball;
class Canvas4 {
public:
static const int num = 100;
vector<Ball> ballCollection;
Ball *myBall;
Ball getBallById(int id) {
return this->ballCollection.at(id)
};
};
class Ball {
friend class Canvas4;
public:
void lineBetween() {
for (int i=0; i<Canvas4::num; i++) {
Ball other = Canvas4::ballCollection.at(i);
//*Invalid use of non-static data member "ballCollection"
}
};
};
*无效使用非静态数据成员"ballCollection"
我想通过Id阅读某些球对象的内容,并用它画一些艺术。
编辑
在另一节课上,我做到了。
#include "canvas4.h" //which contains both classes Ball and Canvas4
Canvas4 canvas4;
如注释中所述,类的静态成员通过在类名上应用::
来访问,非静态成员通过对类的对象(例如)应用.
来访问
struct A
{
int x;
static int y;
};
void f(A a)
{
a.x = 1;
A::y = 2;
};
您正试图访问ballCollection
,就好像它是一个静态成员一样,但事实并非如此。
您需要一个Canvas4类型的类对象来使用Ball类中的非静态成员函数。只有类中限定符为static的成员函数才能以"class::Function"格式使用。
编辑
class Ball {
public:
Canvas4 *cv;
Ball(ofVec2f _org, ofVec2f _loc, float _radius, int _dir, float _offSet, Canvas4 *_cv):
org(_org),loc(_loc),radius(_radius), dir(_dir), offSet(_offSet),cv(_cv){}
void Ball::lineBetween() {
for (int i=0; i<Canvas4::num; i++) {
Ball other = cv->getBallById(i);
float distance = loc.distance(other.loc);
if (distance >0 && distance < d) {
ofLine(loc.x, loc.y, other.loc.x, other.loc.y);
}
}
}
};
有必要在构造函数中初始化类变量,如上所示。
我使用@Igor的建议找到的解决方案只是在Ball类中插入一个指向Canvas的指针:
class Ball {
public:
Canvas4 *cv;
Ball(ofVec2f &_org, ofVec2f &_loc, float _radius, int _dir, float _offSet, Canvas4 &_cv);
void Ball::lineBetween() {
for (int i=0; i<Canvas4::num; i++) {
Ball other = cv->getBallById(i);
float distance = loc.distance(other.loc);
if (distance >0 && distance < d) {
ofLine(loc.x, loc.y, other.loc.x, other.loc.y);
}
}
}
};
相关文章:
- 通过 host() 从 af::array 检索数据会导致错误的数据
- 无法从 SQL Server 检索数据
- sd_journal_send发送二进制数据.如何使用日志检索数据?
- 在 c++ 中使用指向对象的指针检索数据
- 从新实例的向量中检索数据返回 0
- 如何通过串行终端检索数据而不破坏其在 GNU ARM 嵌入式中的基本值?
- QNETWORK停止连接并检索数据
- 如何在 c++ 中从文件中检索数据
- 如何从 linux 二进制文件中存储和检索数据
- ifstream不使用C 中的数组检索数据
- 无法从数组二次表达式中检索数据值
- 从具有多态性的类中检索数据
- 当我将字符串数组从 VBA 传递到 c++ 并将它们用作映射中的键时,为什么我无法从映射中检索数据(使用键)
- 调用readAll()后,不再无法从QIODevices检索数据.缓冲区已冲洗
- glBufferStorage + glGetBufferSubData 用于检索数据
- 如果没有数据,则创建一个包含数据的文本文件,然后读取它以检索数据
- 通过HTTP请求从站点检索数据(使用QT5.4的C++)
- 通过传递一个ID(c++)从数据库中检索数据
- 如何从专用字符串中检索数据
- 使用 QNetworkAccessManager 从 web 检索数据:文件已下载,但 QNetworkReply::r