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;
}

The problem is at if (books != Sales_data()) ... which is where the error is

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 ...;
}