#include "stdafx.h"
#include <memory>
#include <gtest\gtest.h>
class Money
{
public:
explicit Money(int value) :value(value) {} ;
Money(Money&& m) :value(m.returnValue()) {};
Money(const Money &m) = default;
Money operator-(const Money &m) ;
Money operator+(const Money &m);
Money operator=(Money &&m) { return Money(m.returnValue()); };
Money &operator=(const Money &m)=default;
int returnValue() const { return value; };
~Money() = default;
private:
int value;
};
Money Money::operator-(const Money &m)
{
return Money(value - m.returnValue());
}
Money Money::operator+(const Money &m)
{
return Money(value + m.returnValue());
}
Money operator+(std::shared_ptr<Money> money, const Money &m)
{
return Money(money->returnValue() + m.returnValue());
}
class Bank {
public:
Bank(Money m) :propertiesBank(std::make_unique<PropertiesBank>(std::move(m))), c(1000) {};
int returnMoney2() const ;
int returnMoney1() const { return c.returnValue(); };
Money addMoney1(const Money &m);
Money addMoney2(const Money &m);
~Bank() = default;
private:
Money c;
struct PropertiesBank;
std::unique_ptr<PropertiesBank> propertiesBank;
};
struct Bank::PropertiesBank
{
std::shared_ptr<Money> money;
PropertiesBank(Money&& m) :money(std::make_shared<Money>(m)) {};
};
Money Bank::addMoney1(const Money &m)
{
c = c + m;
return c;
}
Money Bank::addMoney2(const Money &m)
{
return propertiesBank->money + m;
}
int Bank::returnMoney2() const
{
return propertiesBank->money->returnValue();
}
int main()
{
Money k(1000);
Bank bank(k);
Money h(1000);
std::cout << bank.returnMoney2() << "\n"; // 1000
std::cout << k.returnValue() << "\n"; // 1000
bank.addMoney1(h);
std::cout << bank.returnMoney1() << "\n"; // 1000, I want 2000
bank.addMoney2(h);
std::cout << bank.returnMoney2() << "\n"; // 1000, I want 2000
system("pause");
return 0;
}
重载操作符+不起作用。我有结果所有操作在“int main()”1000,但我认为我有钱= 1000,k = 1000,bank.returnMoney1()= 2000,bank.returnMoney1()= 2000喜欢在评论中