Versuch, einen überladenen Operator für cout für eine Klasse zu erstellen (Lernen von C++) und die folgenden Fehler zu empfangen: .. \ Vpet.h: 17: 14: Fehler: 'Ostream' in Namespace 'Std 'bezeichnet keinen Typ .. \ VPet.cpp: 48: 6: Fehler: 'ostream' im Namensraum 'std' Name hat keinen TypFehler beim Erstellen von Überladungsoperatoren
ich habe das Gefühl, es einen Syntaxfehler ist, aber ich bin mir nicht sicher. Es scheint korrekt zu sein, so dass es plausibel ist, dass es ein Compiler/IDE-Problem sein könnte. Ich benutze MinGW GCC Compiler mit Eclipse. Code Unten:
Header-Datei (IDE meldet einen Fehler auf der friend
Erklärung
* 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_ */
Klasse Quelldatei (Fehlermeldung von IDE auf std::ostream& operator<<(std::ostream& os, const VPet& vp)
Linie
#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;
}
doh! Das hat das Problem behoben. Danke, Vlad. Wenig peinlich sollte das erwischt haben. Sobald SO mir erlaubt, werde ich Ihre Antwort als Lösung auswählen. – StormsEdge
@StormsEdge Jeder Programmierer kann einen Fehler machen. :) –
'' sollte ausreichen (zumindest in der Kopfzeile) –