在C++中从不同的类检索数据

Retrieving data from different classes in C++

本文关键字:检索 数据 C++      更新时间:2023-10-16

我在使用不同类访问方法和参数时遇到了问题,我以前用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);
        }
    }
}
};