C ++:比较相同类型的操作数类型

时间:2015-04-23 19:14:09

标签: c++ types operators

我只使用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()) {

它说操作数类型具有相同的类型,所以我不太明白问题所在。

1 个答案:

答案 0 :(得分:3)

您需要为您的结构实现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 ...;
}