Перегрузка операторов с ошибкой компиляции - PullRequest
0 голосов
/ 03 февраля 2019

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

Это ошибка компиляции, которую я получаю:

// Point.cpp: 45: 11: ошибка: назначение элемента 'CS170 :: Point :: x'в объекте только для чтения

x + = other.x;(.x выделено)

// Point.cpp: 117: 12: ошибка: назначение элемента 'CS170 :: Point :: y' в объекте только для чтения

y = y-other.y;(.y выделено)

// Point.cpp: 47: 9: ошибка: привязка ссылки типа 'CS170 :: Point &' к 'const CS170 :: Point' отменяет квалификаторы

return * this; (* это выделено)

// Point.cpp: 58: 13: ошибка: невозможно привязать неконстантную ссылку lvalue типа 'CS170 :: Point &' к r-значению типа 'CS170:: Точка '

  return Point(pow(x,other.x),pow(y,other.y)); 

(Точка (pow (x.other.x), мощность (y, other.y) выделена)

Point.cpp: в функции-члене'CS170 :: Point & CS170 :: Point :: operator% (double) ': Point.cpp: 94: 5: ошибка: недопустимые операнды типов' double 'и' double 'для двоичного оператора'% '

x = значение x%; (значение x% подсвечивается)

// Point.cpp: 143: 41: ошибка: нет элемента 'int CS170 :: Point :: Multiply (const CS170 :: Point &)'функция, объявленная в классе 'CS170 :: Point'

int Point :: Multiply (const Point и другие)

// Point.cpp: 76: 31: ошибка: неиспользуемый параметр 'dummy' [-Werror = unused-параметр]

Point & Point :: operator - (пустышка int) (пустышка выделена)

#include "Point.h"  

#include <cmath>    

namespace CS170

{

    const double PI = 3.1415926535897;

    const double EPSILON = 0.00001;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // закрытый член функции

double Point::DegreesToRadians(double degrees) const
{;

    return (degrees * PI / 180.0);

}

double Point::RadiansToDegrees(double radians) const
{

    return (radians * 180.0 / PI);

}

/////////////////////////////////////////////////////////////////////////////// // 16 открытых функций-членов (2 конструктора, 14 операторов)

Point::Point(double X, double Y): x(X), y(Y) { }


Point::Point(){

    x=0.0f;

    y=0.0f;

}
Point& Point::operator+(double value)
{

    x=x+value;

    y=y+value;

    return *this;

}
Point& Point::operator+(const Point& other) const
{

    x+=other.x; 

    y+=other.y;

    return *this;

}

Point& Point::operator-(const Point& other)
{

    return -(other.x), -(other.y) ;

}
Point& Point::operator^(const Point& other) 
{

    return Point(pow(x,other.x),pow(y,other.y));

}
Point& Point::operator++(int dummy)
{

    x++;

    y++;

    return *this;

}

Point& Point::operator++()
{

    ++x;

    ++y;

    return *this;

}

Point& Point::operator--(int dummy)
{

    x--;

    y--;

    return *this;

}

Point& Point::operator--()
{
    --x;

    --y;

    return *this;

}

Point& Point::operator%(double value)
{

    x=x%value;

    y=y%value;

    return *this;

}

Point& Point::operator+=(const Point& other) const
{

    x += other.x;

    y += other.y;

    return *this;

}

Point& Point::operator+=(double value)
{

    return Point(x+value,y+value);

}
Point& Point::operator-(int value)
{

    return Point(x-value,y-value);

}

Point& Point::operator-(const Point& other) const

{

    x=x-other.x;

    y=y-other.y;

// return Point(x-other.x,y-other.y);
    return *this;

}

Point& Point::operator*(const Point& other) const
{

    return Multiply(other);

}

/////////////////////////////////////////////////////////////////////////////// // 2 функции друга (операторы)

std::ostream& operator<< (std::ostream &output, const Point &point)
    { 

        output << "(" << point.x << "," << point.y << ")";

        return output;

    }   

std::istream& operator>>(std::istream &input, Point &point ) 
    { 

        input >> point.x >> point.y;

        return input;            

    }

/////////////////////////////////////////////////////////////////////////////// // 2 не члены, не друзья (операторы)

int Point::Multiply(const Point& other) 
{

    return Point(x*other.x, y*other.y);

}
int Point::Add(const Point& other) 
{           

    return Point(x+other.x, y+other.y);

}


}

1 Ответ

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

Задача 1

Вам необходимо сделать функцию-член operator+= функцией-не const.

Point& Point::operator+=(const Point& other)  // No const
{
    x += other.x;

    y += other.y;

    return *this;    
}

Функция изменяет объект, для которого вызывается функция,Не имеет смысла делать ее const функцией-членом.

Задача 2

  • Функция operator+ должна возвращать объект, а не ссылку на объект.
  • Его реализацию необходимо изменить, чтобы он изменил текущий объект.
  • Реализацию можно упростить с помощью оператора +=.

Вотобновленная версия.

Point Point::operator+(const Point& other) const
{
    Point ret(*this);
    return (ret += other);
}

Задача 3

Функция operator^ должна возвращать объект, а не ссылку.

Point Point::operator^(const Point& other) 
{
    return Point(pow(x,other.x),pow(y,other.y));
}

При использовании return Point(...);, это не может быть ссылка на объект.

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