Przeciążenie operator+

0

Mam pytanie jak przeciązyć operator+:

 
int main()
{
    Przedmiot P1("Matematyka",6);
    Przedmiot P2 = P1;
    Przedmiot P3("Automaty",11);;

    P3.wypisz();
    6+P3; // chodzi o to (zwiększyć ilość w obiekcie P3 o 6)
    P3+6;// z tym nie mam problemu 
    return 0;
}
0

w pliku nagłówkowym swojej klasy piszesz funkcję:

Przedmiot operator+(const Przedmiot& _param2) const
{
     return Przedmiot(a +_param2.b, a + _param2.b);
}

o ile konstruktor wygląda mniej-więcej tak:

Przedmiot(a, b);

0

ja proponuję taki układ

#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>

struct A
{
	A& operator+=(A const& rhs) {
		x += rhs.x;
		return *this;
	}

	friend A operator+(A lhs, A const& rhs) {
		return lhs += rhs;
	}

	int x;
};

int main()
{
	A a1 { 2 };
	A a2 { 3 };

	std::cout << (a1 + a2).x;

	return 0;
}

http://melpon.org/wandbox/permlink/3wbFUjfqrdTcRFh2

0

6+P3; Ma działać w funkcji main tak jak napisałem wyżej, mój wykładowca sobie tak zażyczył.
P3 jest obiektem klasy Przedmiot

1
#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>

struct A
{
	A& operator+=(int val) {
		x += val;
		return *this;
	}

	friend A operator+(A lhs, int val) {
		return lhs += val;
	}

	friend A operator+(int val, A lhs) {
		return lhs += val;
	}

	int x;
};

int main()
{
	A a1 { 2 };

	std::cout << (1 + a1).x;
	std::cout << std::endl << (a1 + 2 + 3).x;
        std::cout << std::endl << (-5 + a1 + 3).x;

	return 0;
}

http://melpon.org/wandbox/permlink/7qITessC3ZUSuaVu

0

Metodą prób i błędów chciałem uzyskac takie coś:

 
//Przedmiot.h
friend void operator+(int,Przedmiot &);
//Przedmiot.cpp

void operator+(int l,Przedmiot & P)
{
    P.ilosc+=l;
}

Dzięki za naprowadzenie gośćabc

1 użytkowników online, w tym zalogowanych: 0, gości: 1