创建重载运算符时出错
Error creating overloading operators
尝试为类的 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;
// ^^^^^^^^^^^^^
}
相关文章:
- 在 myVector 类中重载运算符 + 时出错
- 使用运算符调用 void 函数时出错<set>
- 通过 [] 运算符访问unordered_map时出错
- 在重载 + 和 - 运算符时出错
- 重载运算符时出错<在 sf::Vector 中
- 将运算符<<与隐式转换的非基本数据类型一起使用时出错
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 令牌之前缺少二进制运算符 "#" 当 #define 在 #if 内时出错
- 在运算符中将联合作为参数传递时出错<<
- 迭代器关系运算符出错(带单独链接和迭代器的自定义哈希表)
- 尝试重载模板类友元<<运算符时出错
- 使用 getline 重载 istream 运算符>> 会出错
- 灵气:用期望运算符替换序列时出错
- 在类外部定义显式运算符 bool() 时出错
- 擦除矢量中的对象时出错.如何将移动作业运算符添加到我的类中
- 过载运算符出错>>
- 在使用C (Microsoft vs)中使用指针和新运算符时出错
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- static_cast为int时删除布尔运算符时出错
- 为什么我会出错?运算符[]过载