\ main.cpp | 103 |错误:不匹配&#39;运算符&lt;&lt;&lt;&#39; (操作数类型是&#39; std :: ostream {aka std :: basic_ostream <char>}&#39;和#39; Person&#39;)

时间:2017-05-13 15:48:19

标签: c++ operator-overloading cout

这是我的第一个问题,所以请承担我所犯的任何格式错误,我会尝试编辑它们:)

我有这个函数找到一些数据类型为X的三个变量的最大值并返回它。

template <class X>
X fmax(X a, X b, X c)
{
    X temp=a;
    if (b>temp)
       temp=b;
    if(c>temp)
       temp=c;
    return temp;
}

然后有一个看起来像这样的人类

class Person
{
private:
    char* name;
    int height;
    char gender;
public:
    Person(){}
    Person(char * name,int height, char gender)
    {
        int sz=strlen(name);
        this->name= new char [sz];
        strcpy(this->name,name);
        this->height=height;
        this->gender=gender;
    }
    void setName(char* name)
    {
        int sz=strlen(name);
        this->name= new char [sz];
        strcpy(this->name,name);
    }
    void setHeight(int h){this->height=h;}
    void setGender(char g){this->gender=g;}
    char* getName(){return this->name;}
    int getHeight(){return this->height;}
    char getGender(){return this->gender;}

    Person operator= (Person p)
    {
        int sz=strlen(p.getName());
        this->name= new char [sz];
        strcpy(this->name,p.getName());
        this->height=p.getHeight();
        this->gender=p.getGender();
        return *this;

    }
    bool operator> (Person p)
    {
        if(this->getHeight()>p.getHeight())//The persons should be compared using their heights.
            return true;
        return false;
    }
};

我也淹没了ostream:

ostream &operator<<(ostream &mystream, Person &p)
{
mystream<<"The person's name is: "<<p.getName()<<endl;
mystream<<"The person's height is: "<<p.getHeight()<<endl;
mystream<<"The person's gender is: "<<p.getGender()<<endl;
return mystream;
}

但是我的主要错误是

int main()
{
    Person a("Zacky",178,'m');
    Person b("Jimmy",199,'m');
    Person c("Matt",200,'m');
    Person d=fmax(a,b,c);
    cout<<d<<endl;
    cout<<fmax(a,b,c);<<endl;//the error strikes here.
    return 0;
}

显然我可以在使用fmax函数初始化对象d后对该对象进行cout但不能直接输出该函数返回的内容。关于我需要解决什么的任何想法?

P.S。如果之前有人问我,我很遗憾,我搜索了网站并没有找到类似的东西:/

1 个答案:

答案 0 :(得分:0)

您需要更改以下内容:

由于fmax()返回不可变的 rvalue ,您应该使用

ostream &operator<<(ostream &mystream, const Person &p);
                                    // ^^^^^

作为输出操作符重载的签名(我建议一般这样做。)

反过来,这需要使你的getter函数const成员函数:

class Person
{
   // ...
    const char* getName() const {return this->name;}
    int getHeight() const {return this->height;}
    char getGender() const {return this->gender;}
};