我为我的一个班级制作了一个项目,我很确定我几乎完成了这个项目。基本上我必须输入2人的门票,我必须找到最高和最低价格。我需要重载*和/运算符来修复项目的问题。此外,通过教师的指示,friend
声明是此项目的必要条件。
现在,对于这个问题。我试图将正确的票证变量(t1或t2)存储到t3中,这样我就可以将它返回到主变量。当我使用" ="要设置t1到t3,它说"没有可行的超载' ='"。以下是我的代码:
#include <iostream>
using namespace std;
class ticket
{
public:
ticket();
double input();
double output();
friend ticket operator *(const ticket &t1, const ticket &t2);
friend ticket operator /(const ticket &t1, const ticket &t2);
private:
void cost();
string name;
double miles, price;
int transfers;
};
int main()
{
ticket customer1, customer2, customer3;
//------------------------------------------------
cout << "*** Customer 1 ***" << endl;
customer1.input();
cout << "--- Entered, thank you ---" << endl;
cout << "*** Customer 2 ***" << endl;
customer2.input();
cout << "--- Enter, thank you ---" << endl;
//------------------------------------------------
//------------------------------------------------
cout << "Testing of the * operator: " << endl;
customer3 = customer1 * customer2;
cout << "*** Database printout: ***" << endl;
customer3.output();
cout << endl;
cout << "--- End of Database ---" << endl;
//------------------------------------------------
//------------------------------------------------
cout << "Testing of the / operator:" << endl;
customer3 = customer1 / customer2;
cout << "*** Database printout: ***" << endl;
customer3.output();
cout << endl;
cout << "--- End of Database ---" << endl;
//------------------------------------------------
return 0;
}
ticket operator *(const ticket &t1, const ticket &t2)
{
ticket t3;
if (t1.price > t2.price)
t3 = t1.price;
else
t3 = t2.price;
return t3;
}
ticket operator /(const ticket &t1, const ticket &t2)
{
ticket t3;
if (t1.price < t2.price)
t3 = t1.price;
else
t3 = t2.price;
return t3;
}
ticket::ticket()
{
}
double ticket::input()
{
cout << "Miles? ";
cin >> miles;
cout << endl << "Transers? ";
cin >> transfers;
cout << endl << "Name? ";
cin >> name;
cost();
cout << endl << "Price is: " << price << endl;
return miles;
}
double ticket::output()
{
cout << name << '\t' << miles << "mi \t " << transfers << " transfers \t" << price;
return miles;
}
void ticket::cost()
{
price = (.5 * miles) - (50 * transfers);
}
答案 0 :(得分:5)
您没有为operator=
定义ticket
,其中以double为参数。因此,您无法为ticket
个对象分配双打。
答案 1 :(得分:1)
这就是我得到相同编译错误的方法。我将我的一个getter函数标记为const
,而我仍想修改类成员变量。请参阅以下简单示例:
class CPath {
private:
std::string m_extension;
public:
std::string GetExtension() const {
if (m_extension.length()==0) {
m_extension = "txt";
}
return m_extension;
}
}
在这种情况下,我们有两个解决方案:
1)在函数定义中删除const
修饰符;
2)将属性m_extension
标记为mutable
。
答案 2 :(得分:0)
您可能希望拥有会员功能
set_price(const& double price)
所以你可以改变这样的错误代码,这样会更好
if (t1.price > t2.price)
t3.set_price(t1.price);
else
t3.set_price(t2.price);