2014-09-06 3 views
-2

다른 클래스를 사용하는 액세스 방법과 매개 변수에 문제가 있습니다. Java로 코딩 했으므로 다른 범위의 함수를 사용하는 데 문제가 없습니다.C++에서 다른 클래스의 데이터 가져 오기

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; 
+0

, 당신은 Canvas4''클래스의 인스턴스를 필요 그 비 정적 멤버들. –

+0

Canvas4 canvas4를 설치합니다. 메인 클래스. – cleliodpaula

+0

그래서 그 인스턴스에 대한 참조를'lineBetween' 또는이 라인을 따라 무엇인가에 대한 매개 변수로 전달하십시오. 프로그램에 여러 캔버스가있을 수 있습니다. 'lineBetween'이 볼 컬렉션을 알아야한다고 생각 하는게 또 뭐죠? –

답변

0

Ball 클래스의 비 정적 멤버 함수를 사용하려면 Canvas4 유형의 클래스 객체가 필요합니다. 클래스에서 한정자를 정적으로 갖는 멤버 함수 만 "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); 
     } 
    } 
} 
}; 

위와 같이 생성자에서 클래스 변수를 intilaize 필요가있다.

0

댓글에서 이미 언급했듯이 클래스의 정적 멤버는 클래스 이름에 ::을 적용하고 클래스의 객체에 .의 비 정적 멤버를 적용하여 액세스합니다.

struct A 
{ 
    int x; 
    static int y; 
}; 

void f(A a) 
{ 
    a.x = 1; 
    A::y = 2; 
}; 

ballCollection은 (는) 정적 멤버 인 것처럼 액세스하려고 시도하고 있습니다.

-1

단순히 볼 클래스에서 캔버스에 대한 포인터를 삽입 한 @Igor에 의해 제안을 사용하여 발견 솔루션 : 당신이 액세스 할 수

그냥 자바와 같은
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); 
     } 
    } 
} 
}; 
관련 문제