перегрузка c ++ <использование функции друга в C ++ для нескольких классов? - PullRequest
0 голосов
/ 14 ноября 2009

Я экспериментирую с перегрузкой оператора <(я добавлю> позже) в качестве средства проверки, находится ли одна из золотых рыбок (см. Код ниже) на территории другой (территории могут перекрываться). Я получаю несколько ошибок компиляции с помощью кода - в первую очередь, чтобы иметь возможность доступа к закрытым переменным, хотя я сделал перегруженный оператор дружественной функцией для них обоих.

Возможно, я ошибаюсь в синтаксисе?

    /* fish program:
each fish will start out with a static size and a territory.
they may attack each other, in which case the outcomes with depend on 
1) their location (ie. if the attacking fish is on the territory of another goldfish
2) the relative size of the two fish

depending on the outcome of the attack - the fish may retreat or triumph.
triumph will increase its territory.
*/




#include <iostream>
using namespace std;


class point {
private:
  float x;
  float y;

public: 
  point(float x_in, float y_in) { //the 2 arg constructor 
    x = x_in;
    y = y_in;
  }

  friend bool operator< ( const point &point_a, const territory &the_territory);


};

class territory {

private:
  point ne, sw;

public:
  territory(float x_ne, float y_ne, float x_sw, float y_sw) 
    : ne(x_ne, y_ne), sw(x_sw,y_sw) {
    cout << ne.x << " and " << ne.y <<endl; //debug
  }  

  friend bool operator< ( const point &point_a, const territory &the_territory) {
    if((point_a.x < the_territory.ne.x && point_a.x > the_territory.ne.x) && 
       (point_a.y < the_territory.ne.y && point_a.y > the_territory.ne.y))
      return true;
  }




};

class goldfish {
private:
  float size;
  point pos;
  territory terr;

public:

  goldfish(float x, float y) : pos(x,y), terr(x-1,y-1,x+1,y+1)  { //constructor
       size = 2.3;
}

  void retreat() { //what happens in the case of loss in attack

  }
  void triumph() {
  }

  void attack() {

  }
};




int main() {



  goldfish adam(1,1); // fish1
  goldfish eve(1.2,1.2); // fish2




}

Ответы [ 2 ]

1 голос
/ 14 ноября 2009

Я не проверил логику вашей программы, но есть несколько простых замечаний. Я прокомментировал дополнения:

class territory; // declare the class used in operator<
class point {
private:
    float x;
    float y;

public: 
    point(float x_in, float y_in) {
        x = x_in;
        y = y_in;
    }

    float getx() { return x;} // add public "getter" for x
    float gety() { return y;} // same for y

    friend bool operator< ( const point &point_a, const territory &the_territory);
};

Кроме того, не забудьте использовать методы, которые мы определили выше:

territory(float x_ne, float y_ne, float x_sw, float y_sw) 
    : ne(x_ne, y_ne), sw(x_sw,y_sw) {
        // access x and y through getters
        cout << ne.getx() << " and " << ne.gety() <<endl;
}  
0 голосов
/ 14 ноября 2009

Вы не можете получить доступ к закрытым членам точки в конструкторе territory (даже в целях отладки). Также вам может потребоваться перевести объявление класса territory, прежде чем объявить класс point. В противном случае компилятор может пожаловаться на объявление оператора друга, так как он использует territory в качестве типа аргумента. UPD: Просто следуйте примеру AraK, я печатал и не видел его

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...