创建重载运算符时出错

Error creating overloading operators

本文关键字:出错 运算符 重载 创建      更新时间:2023-10-16

尝试为类的 cout 创建一个重载运算符(学习C++)并收到以下错误:..\Vpet.h:17:14:错误:命名空间"std"中的"ostream"未命名类型..\VPet.cpp:48:6:错误:命名空间"std"中的"ostream"未命名类型

我有一种感觉,这是一个语法错误,但我不确定。 它似乎是正确的,因此它可能是一个编译器/IDE问题。 我正在使用带有Eclipse的MinGW GCC编译器。 代码如下:

头文件(IDE 通知friend声明上出现错误

* Vpet.h
 *
 *  Created on: May 18, 2016
 *      Author: TAmend
 */
#ifndef VPET_H_
#define VPET_H_

class VPet
{
    public:
    friend std::ostream& operator<<(std::ostream& os, const VPet& vp);
    // Constructors (Member Functions)
    VPet(int weight, bool hungry);
    //Default value in case the user creates a virtual pet without supplying parameters
    VPet();
    // Member functions
    void feedPet(int amountOfFood);
    bool getHungry();
    double getWeight();
    private:
    // Data Members
    double weight;
    bool hungry;
};

#endif /* VPET_H_ */

类源文件(来自 IDE 的错误通知std::ostream& operator<<(std::ostream& os, const VPet& vp)

#include "Vpet.h"
#include <cmath>

//Creation of our constructor (you can leave out the initializer list,
//but without it you're initializing to default and then overriding (operation twice))
VPet::VPet(int w, bool hun):weight(w),hungry(hun)
{

}
VPet::VPet():weight(100), hungry(true)
{
}
//Member Functions
void VPet::feedPet(int amt)
{
    if(amt >= (0.5 * weight))
    {
        hungry = false;
    }
    else
    {
        hungry = true;
    }
    weight = weight + (0.25 * amt);
}
double VPet::getWeight()
{
    return weight;
}
bool VPet::getHungry()
{
    return hungry;
}
std::ostream& operator<<(std::ostream& os, const VPet& vp)
{
    std::string hungerStatus = "";
    if(vp.hungry)
    {
        hungerStatus = "hungry";
    }
    else
    {
        hungerStatus = "not hungry";
    }
    return os << "weight: " << vp.weight << " hunger status: " << hungerStatus << std::endl;
}

您需要在标头中包含标头<iostream> Vpet.h

例如

* Vpet.h
 *
 *  Created on: May 18, 2016
 *      Author: TAmend
 */
#ifndef VPET_H_
#define VPET_H_
#include <iostream>
//...

同样在包含运算符定义的模块中,您需要包含标头<string>

标头<cmath>是多余的,如果您不打算对对象进行一些数学运算。

请注意,最好将不更改对象状态的成员函数声明为常量。例如

bool getHungry() const;
double getWeight() const;

输出运算符可以在没有函数说明符的情况下声明,friend使用限定符 const 声明的 getter,如我所示。

例如

std::ostream& operator<<(std::ostream& os, const VPet& vp)
{
    std::string hungerStatus;
    if(vp.getHungry())
    //    ^^^^^^^^^^^
    {
        hungerStatus += "hungry";
    }
    else
    {
        hungerStatus += "not hungry";
    }
    return os << "weight: " << vp.getWeight() << " hunger status: " << hungerStatus << std::endl;
    //                         ^^^^^^^^^^^^^
}