作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在为我的一门类(class)做一个项目,我很确定我几乎完成了这个项目。基本上我必须输入 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);
}
最佳答案
您没有为 ticket
定义一个 operator=
,它接受一个 double 作为它的参数。因此,您不能将 double 分配给 ticket
对象。
关于c++ - "No viable overloaded ' = ' "为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161374/
我是一名优秀的程序员,十分优秀!