C++:比较相同类型的操作数类型
C++: comparing operand types of the same type
我只用了大约一个星期的C++自学。我尝试搜索类似的问题,但找不到。但是,这可能是由于不知道用于我的问题的适当搜索词。
我定义了以下结构:
struct Sales_data {
// empty bracket initializes to empty string
std:: string bookNo{};
unsigned units_sold = 0;
double revenue = 0.0;
};
在我的int main() {}
中,我使用if
循环来检查book
是否为非空,Sales_data books;
之前已经声明过。也就是说,我有
#include <iostream>
#include <string>
struct Sales_data {
// empty bracket initializes to empty string
std:: string bookNo{};
unsigned units_sold = 0;
double revenue = 0.0;
};
int main(){
Sales_data books;
double price = 0.0;
// some ostream code here
for (int i = 0; i >= 0; ++i) {
// The for loop keeps track and counts the books
while (std::cin >> books.bookNo >> books.units_sold >> price) {
/*
* while loop to allow the user to input as many books as they would
* like
*/
if (books != Sales_data()) {
// if books is not empty print which number book for i
i += 1;
std::cout << "Book " << i << " is " << books << std::endl;
}
}
}
return 0;
}
问题出在错误所在
if (books != Sales_data()) ...
error: no match for ‘operator!=’ (operand types are
‘Sales_data’ and ‘Sales_data’)
if (books != Sales_data()) {
它说操作数类型具有相同的类型,所以我不太明白问题是什么。
您需要
为结构实现operator!=
。
struct Sales_data
{
...
bool operator!=(const Sales_data& other)
{
// Logic to determine if sales data are not equal
return ...;
}
}; // end definition of struct Sales_data
或者这可以作为独立运算符实现
bool operator!=(const Sales_data& data1, const Sales_data& data2)
{
// Logic to determine if the two instances are not equal
return ...;
}
相关文章:
- 与'operator='不匹配(操作数类型'String'且"void")
- 不正确的操作数类型 MSVC
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- 错误:'operator>'不匹配(操作数类型为 'Student' 和 'Student'
- 与"运算符>>"不匹配(操作数类型为"QDataStream"和"QJsonObject")
- 与'operator<<'不匹配(操作数类型'std::ostream {aka std::basic_ostream<char>}'
- c++运算符重载-我实际返回的操作数类型是什么
- 没有运算符"=="与这些操作数匹配。操作数类型为:int == type_name'
- 与"operator<<"不匹配(操作数类型'std::ostream'
- C++ 重载:[错误] 与'operator='不匹配(操作数类型为 'String' 和"字符串")
- 错误:与"运算符>>"不匹配(操作数类型为"std::istream
- 与"运算符[]"不匹配(操作数类型为"std::unique_ptr<std::vector<int> >"和"int")
- 错误:与'operator='不匹配(操作数类型为 'PlDrustvo' 和"PlDrustvo")|
- 错误:与'operator='不匹配(操作数类型为"std::map<int、double>::iterator
- 没有运算符匹配这些操作数;操作数类型为: std::istream >> const char [5]
- \main.cpp|103|error: 与"operator<<"不匹配(操作数类型为"std::ostream {aka std::basic_ostream<char&g
- 重载运算符'<<'的使用不明确(操作数类型'ostream'(也称为"basic_ostream<char>")和"Person")
- 错误:与"运算符[]"不匹配(操作数类型为"QVector<int>"和"QCharRef")
- 错误:如果(object1 == object2),“操作器==”无匹配(操作数类型为“ const class”和“
- 没有运算符"="匹配这些操作数操作数操作数类型为 std::basic_ostream<char、std::char_traits<char>> = int