vendredi 27 mai 2016

Error creating overloading operators

Attempting to create an overloaded operator for cout for a class (learning C++) and receiving the following errors: ..\Vpet.h:17:14: error: 'ostream' in namespace 'std' does not name a type ..\VPet.cpp:48:6: error: 'ostream' in namespace 'std' does not name a type

I have a feeling it's a syntax error, but i'm not sure. It appears to be correct so it's plausible that it could be a compiler/IDE problem. I'm using MinGW GCC compiler with Eclipse. Code Below:

Header File (IDE notifies of an error on the friend declaration

* 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_ */

Class Source File (Error notification from IDE on std::ostream& operator<<(std::ostream& os, const VPet& vp) line

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

Aucun commentaire:

Enregistrer un commentaire