创建重载运算符时出错

时间:2016-05-27 12:14:49

标签: c++ eclipse c++11 syntax compiler-errors

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

我觉得这是一个语法错误,但我不确定。它似乎是正确的,因此它可能是编译器/ 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_ */

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

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

1 个答案:

答案 0 :(得分:4)

您需要在标题<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;
    //                         ^^^^^^^^^^^^^
}