Функции перегрузки оператора - PullRequest
0 голосов
/ 04 февраля 2019

Я застрял в отношении 2 умножения, не являющегося членом, 2 умножения, не являющегося другом, и добавления функций перегрузки операторов.Я не уверен, как это сделать.Может ли кто-нибудь помочь мне решить эту проблему?Обратитесь к моим кодам ниже.Заранее спасибо!

Выход компилятора:

Point.cpp:208:19: error: passing ‘const CS170::Point’ as ‘this’ argument discards qualifiers [-fpermissive]

    return other + value;
                   ^~~~~

Point.cpp: In function ‘CS170::Point CS170::

operator*(double, const CS170::Point&)’:

Point.cpp:215:10: error: ‘double CS170::Point::x’ is private within this context

   result.x = value * x;
          ^

Point.cpp:215:22: error: ‘x’ was not declared in this scope

   result.x = value * x;
                      ^
Point.cpp:216:10: error: ‘double CS170::Point::y’ is private within this context

   result.y =  value * y;
          ^

Point.cpp:216:23: error: ‘y’ was not declared in this scope
   result.y =  value * y;

Point.h

  #include <iostream> // istream, ostream

  namespace CS1100
{
  class Point
  {
   public:
  // Point(double X, double Y);    // Constructors (2)
  explicit Point(double x, double y); 

   Point();

   Point operator+(const Point& other)const ;

   Point& operator+(double value);


   Point operator*(double value) ;

   Point operator%(double value);


   Point operator-(const Point& other)const ;

   Point operator-(double value);

   Point operator^(const Point& other);

   Point operator+=(double value);
   Point& operator+=(const Point& other) ;

   Point& operator++();
   Point operator++(int); 

   Point& operator--(); 
   Point operator--(int); 

   Point& operator-();


        // Overloaded operators (14 member functions)
   friend std::ostream &operator<<( std::ostream &output, const Point &point );
    friend std::istream &operator>>( std::istream  &input, Point &point );

    // Overloaded operators (2 friend functions)

private:
  double x; // The x-coordinate of a Point
  double y; // The y-coordinate of a Point

    // Helper functions
  double DegreesToRadians(double degrees) const;
  double RadiansToDegrees(double radians) const;
 };

 // Point& Add(const Point& other); // Overloaded operators (2 non-member, non-friend functions)
    // Point& Multiply(const Point& other);
    Point operator+( double value, const Point& other );
    Point operator-( double value, const Point& other );

Мой исходный код:

///////////////////////////////////////////////////////////////////////////////
// 2 non-members, non-friends (operators)


double operator+( double value, const Point& other ) 
{
     return other + value;
}   

double operator*( double value, const Point& other ) 
{

    Point result;
    result.x = value * x;
    result.y =  value * y;
    return result;
}   

1 Ответ

0 голосов
/ 04 февраля 2019

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

Однако выиметь целый ряд функций, которые не обязательно должны быть членами, например:

class Point
{
public:
    Point operator+(const Point& other) const
    {
        return Point(x + other.x, y + other.y);
    }
};

Сделать из них все функции свободными:

class Point { /*...*/ };

Point operator+(Point const& l, Point const& r)
{
    return Point(l.getX() + r.getX(), l.getY() + r.getY());
}

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

class Point
{
public:
    double getX() { return x; };
    double getY() { return y; };
};

Если вы хотите переименовать переменные-члены, например, добавив префикс, вы можете выполнитьдругой шаблон:

class Point
{
    double m_x, m_y;
public:
    double x() { return m_x; };
    double y() { return m_y; };

    void x(double v) { m_x = v; }; // the corresponding setter
                                   // (for illustration, you might not need it)
};

Этот последний шаблон также довольно распространен.Преимущество в том, что оно пропускает явный префикс get или set, а недостаток в том, что он точно теряет эту явность ... Решите, какой из них вы предпочитаете.Однако важнее, чем личные предпочтения, является последовательность, поэтому, если, например, существует соглашение или общепринятая практика компании, следуйте этому ...

Некоторые из ваших операторов должны будут оставаться участниками, хотя это все те, кто изменить текущий объект:

class Point
{
public:
    Point& operator+=(const Point& other) /* const */ // NEEDS to be non-const
    {
        x += other.x;
        y += other.y;
        return *this; // <- very good hint to spot the ones needing to stay members
    }
};

Если у вас есть открытый конструктор copy , вы можете повторно использовать operator+= для определения operator+:

class Point
{
public:
    Point(Point const& other) : Point(other.x, other.y) { }
};

Point operator+(Point const& x, Point const& y)
{
    Point r(x); // or Point(x.x(), x.y()), if you lack such constructor)
    r += y;
    return r;
}

На самом деле, вы даже можете сэкономить явную копию, приняв один из параметров по значению:

Point operator+(Point x, Point const& y)
//                    ^ no reference
{
    return x += y;
}

Последний скорее для иллюстрации, я бы предпочел две ссылки вданный случай для сохранения симметрии интерфейса ...

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