Cra*_*rty 1 c++ pointers reference operator-overloading
当我重载"=="
和"!="
运算符时,我传递指针作为参数,并调用重载函数,我得到了我期望的结果,但在调试中,我发现在调用期间cout << (fruit1 < fruit);
,我的重载"<"
方法没有被调用.为什么"<"
操作员是唯一没有超载的人?我已经通过了一个基准参数,而不是对其进行测试和DE-引用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 << "...";
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
您operator<
是一个成员函数,这意味着它适用于类型Fruit, const Fruit*
,并且您尝试传递它Fruit*, Fruit*
.
当您将运算符声明为成员函数时,左侧参数隐含为Fruit
.如果你想要别的东西,那么你必须建立一个全局运算符.不幸的是,您需要一个类或枚举类型作为参数,因此您不能有两个指针.
解决这个限制的一种方法.代替
cout << (fruit1 < fruit);
Run Code Online (Sandbox Code Playgroud)
使用
cout << (*fruit1 < fruit);
Run Code Online (Sandbox Code Playgroud)
我也想让你知道这个:
(fruit == fruit1)
Run Code Online (Sandbox Code Playgroud)
比较指针而不是它们指向的指针.在您的情况下,这是两个不同的对象,因此指针比较将始终返回false.