gpt4 book ai didi

c++ - 创建重载运算符时出错

转载 作者:行者123 更新时间:2023-11-30 01:43:33 25 4
gpt4 key购买 nike

尝试为类(学习 C++)创建 cout 的重载运算符并收到以下错误:..\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_ */

类源文件(来自 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;
}

最佳答案

您需要包含 header <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;
// ^^^^^^^^^^^^^
}

关于c++ - 创建重载运算符时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com