【问题标题】:\main.cpp|103|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Person')\main.cpp|103|error: no match for 'operator<<' (操作数类型是 'std::ostream {aka std::basic_ostream<char>}' 和 'Person')
【发布时间】:2017-05-13 15:48:18
【问题描述】:

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

我有这个函数,它找到某个数据类型 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;
}

然后是 Person 类,看起来像这样

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 后计算它,但不能直接计算该函数返回的内容。知道我需要解决什么问题吗?

附:如果之前有人问过这个问题,我感到非常抱歉,我搜索了该网站并没有找到类似的内容:/

【问题讨论】:

    标签: c++ operator-overloading cout


    【解决方案1】:

    您需要更改以下内容:

    由于fmax() 返回一个不可更改的右值,你应该使用

    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;}
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2021-12-17
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多