gpt4 book ai didi

c++ - Visual Studio 编译和检测运算符重载而 g++ 没有

转载 作者:搜寻专家 更新时间:2023-10-31 02:19:29 24 4
gpt4 key购买 nike

我有一个家庭类。我用 house house; 初始化一个新的房子元素,然后我将数据传递给它,然后我计算它:

cout << house;

Couting house 在 Visual Studio 中工作得很好,但出于某种原因,当我尝试使用 g++ 进行编译时收到此错误:

main.cpp:19:57: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>::__ostream_type {aka std::basic_ostream<char>}’ and ‘house’)
cout << "\nnext house to be visited:" << endl << endl << house << endl;

即使我的一个头文件中非常清楚地包含了这个:

friend std::ostream& operator<< (std::ostream& out, house);

如果您能提供任何反馈,我将不胜感激,因为我看不出有什么理由让 g++ 无法看到我的运算符重载函数。

编辑:这是我的运算符重载函数:

std::ostream& operator<< (std::ostream& out, const house& house)
{
out << "Address: " << house.getAddress() << std::endl
<< "Square Feet: " << house.getSqrFt() << std::endl
<< "Bedrooms: " << +house.getBedrooms() << std::endl
<< "Bathrooms: " << house.getBathrooms() << std::endl
<< "Description: " << house.getDescription() << std::endl;
return out;
}

这是我的家庭类:

#ifndef HOUSE
#define HOUSE
class house
{
public:
house();
house(const char[], const unsigned short& sqrFt, const unsigned char& bedrooms, const float& bathrooms, const char[]);
house(house & obj);
house(house *& obj);
~house();
char * getAddress() const;
unsigned short getSqrFt() const;
unsigned char getBedrooms() const;
float getBathrooms() const;
char * getDescription() const;
void setAddress(const char address[]);
void setSqrFt(const unsigned short& sqrFt);
void setBedrooms(const unsigned char& bedrooms);
void setBathrooms(const float& bathrooms);
void setDescription(const char description[]);
void setEqual(house &, house*);
private:
char * address;
unsigned short sqrFt;
unsigned char bedrooms;
float bathrooms;
char * description;
};
#endif

这是我的队列类,其中包含我的运算符重载函数的声明:

#ifndef QUEUE
#define QUEUE
#include <ostream>
#include "house.h"

class queue
{
public:
queue();
queue(queue & obj);
~queue();
void enqueue(house *& item);
bool dequeue(house & item);
void print() const;
void readIn(const char []);
private:
struct node
{
node();
house* item;
node * next;
};
node * head;
node * tail;
void getLine(std::ifstream&, char key[]);
friend std::ostream& operator<< (std::ostream& out, const char[]);
//friend std::ostream& operator<< (std::ostream& out, house *&);
friend std::ostream& operator<< (std::ostream& out, const house&);
};
#endif

最佳答案

问题是您要声明您的 operator<<对于 house在错误的类中:

class queue
{
friend std::ostream& operator<< (std::ostream& out, const house&);
};

当您在类中声明友元运算符时 X , 只有当我们寻找 X 时,对该运算符的查找才会成功.有了这个声明,我们只会找到 operator<<(std::ostream&, const house&)当我们查找 queue - 但这是不可能的,因为没有一个参数是 queue所以我们永远不会尝试用一个来查找它。

您需要将您的声明移动到正确的类:

class house {
friend std::ostream& operator<< (std::ostream& out, const house&);
};

关于c++ - Visual Studio 编译和检测运算符重载而 g++ 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33375770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com