【发布时间】:2013-10-08 01:45:40
【问题描述】:
当我重载 "==" 和 "!=" 运算符时,我将指针作为参数传递,重载函数被调用,我得到了我期望的结果,但在调试中我发现在调用 cout << (fruit1 < fruit); 期间,我的重载函数"<" 方法未被调用。为什么"<" 运算符是唯一没有被重载的?我已经传递了一个引用参数来测试它并在函数调用中取消引用 fruit 和 fruit1 并且它工作正常,所以函数本身工作。是这些单个运算符的属性还是 "!=" 和 "==" 方法是内联的这一事实允许它们工作?
CPP
#include "Fruit.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
【问题讨论】:
-
为什么要重载运算符以获取指针而不是引用?
标签: c++ pointers reference operator-overloading