Visual Studio Compiling&检测Operater重载虽然g ++没有

时间:2015-10-27 18:26:01

标签: c++ c++11 visual-studio-2013 g++

我有一个家庭课。我使用house house;初始化一个新的house元素然后我将数据传递给它,然后我cout它:

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

1 个答案:

答案 0 :(得分:2)

问题是您在错误的班级中声明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&);
};