当我重载"=="
and"!="
运算符时,我将指针作为参数传递,重载的函数被调用,我得到了我期望的结果,但在调试中我发现在我的调用期间cout << (fruit1 < fruit);
,我的重载"<"
方法没有被调用。为什么"<"
操作员是唯一没有被重载的?我已经传递了一个引用参数来测试它并在函数调用中取消引用它fruit
并且fruit1
它工作,所以函数本身工作。是这些单个运算符的属性还是允许它们工作的"!="
and"=="
方法是内联的事实?
CPP
#include "水果.h"
using namespace std;
Fruit::Fruit(const Fruit &temp )
{
name = temp.name;
for(int i = 0; i < CODE_LEN - 1; i++)
{
code[i] = temp.code[i];
}
}
bool Fruit::operator<(const Fruit *tempFruit)
{
int i = 0;
while(name[i] != NULL && tempFruit->name[i] != NULL)
{
if((int)name[i] < (int)tempFruit->name[i])
return true;
else if((int)name[i] > (int)tempFruit->name[i])
return false;
i++;
}
return false;
}
std::ostream & operator<<(std::ostream &os, const Fruit *printFruit)
{
int i = 0;
os << setiosflags(ios::left) << setw(MAX_NAME_LEN) << printFruit->name << " ";
for(int i = 0; i < CODE_LEN; i++)
{
os << printFruit->code[i];
}
os << endl;
return os;
}
std::istream & operator>>(std::istream &is, Fruit *readFruit)
{
string tempString;
is >> tempString;
int size = tempString.length();
readFruit->name = new char[tempString.length()];
for(int i = 0; i <= (int)tempString.length(); i++)
{
readFruit->name[i] = tempString[i];
}
readFruit->name[(int)tempString.length()] = '\0';
for(int i =0; i < CODE_LEN; i++)
{
is >> readFruit->code[i];
}
return is;
}
void main()
{
Fruit *fruit = new Fruit();
Fruit *fruit1 = new Fruit();
cin >> fruit;
cin >> fruit1;
cout << (fruit == fruit1);
cout << (fruit != fruit1);
cout << (fruit1 < fruit);
cout << "...";
}
H
#ifndef _FRUIT_H
#define _FRUIT_H
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
#include "LeakWatcher.h"
enum { CODE_LEN = 4 };
enum { MAX_NAME_LEN = 30 };
class Fruit
{
private:
char *name;
char code[CODE_LEN];
public:
Fruit(const Fruit &temp);
Fruit(){name = NULL;};
bool operator<(const Fruit *other);
friend std::ostream & operator<<(std::ostream &os, const Fruit *printFruit);
bool operator==(const Fruit *other){return name == other->name;};
bool operator!=(const Fruit *other){return name != other->name;};
friend std::istream & operator>>(std::istream& is, Fruit *readFruit);
};
#endif