利用构造函数、析构函数和打印对象- c++
Utilizing constructor, destructor, and printing off objects - c++
请阅读评论
基本上,我试图找出对象构造函数,析构函数和类。我创建了一个类,其中包含一些公共成员变量和一些私有成员变量。此时,我只在代码中使用了public成员。
我的问题是,简单地说,我如何利用构造函数、析构函数,并将对象的信息打印到控制台。
谢谢。
#include <iostream>
// Class -> NPC
// Contains generic stats for an NPC in a game
class NPC
{
public:
char name;
int age;
char favoriteItem;
private:
char quest;
char nemesis;
int karma;
}
// Object Constructor
NPC::NPC (char newName, int newAge, char newFavoriteItem)
{
name = newName;
age = newAge;
favoriteItem = newFavoriteItem;
}
// Object Deconstructor
NPC::~NPC()
{
// Do nothing
}
// Here I would like to create a new NPC, bob, with a name of "Bob", age of 28, and his favorite items being a Sword
// Next, I attempt to use this information as output.
int main()
{
NPC bob("Bob",28, "Sword");
std::cout << bob << std::endl;
}
将字符(只有一个字符)固定为std::string。我增加了初始化列表和std::ostream &operator <<
操作符。
#include <iostream>
#include <memory>
#include <string.h>
class NPC
{
public:
std::string name;
int age;
std::string favoriteItem;
NPC(std::string const& name, int age, std::string favoriteItem)
: name(name), age(age), favoriteItem(favoriteItem)
{};
private:
char quest;
char nemesis;
int karma;
};
std::ostream &operator << (std::ostream &os, NPC const& npc)
{
os << npc.name << " " << npc.age << " " << npc.favoriteItem << "n";
return os;
};
int main()
{
NPC npc("Bob", 28, "Sword");
std::cout << npc;
return 0;
}
相关文章:
- 将对象放入地图后打印对象
- 打印对象的映射,其中另一个对象作为键
- 如何在C++中打印对象向量的内容
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- 使用成员函数打印对象
- 如何在C++中转换可打印对象中的对象
- 打印对象矢量的意外输出
- 如何使用 is_invocable() 创建用于重载<<打印对象的模板?
- 运算符重载<<,打印对象矢量时遇到问题
- 我正在尝试循环浏览对象的向量并打印对象的每个元素
- 在更改对象值后,打印对象数组仍会给出相同的值
- 声明并使用静态列表来打印对象(在c++中)
- 为什么写入临时字符串流对象只打印对象地址
- 打印对象数组
- 有没有一种方法可以打印对象的位表示
- OpenCV - 仅在绘制单应性时打印对象名称
- 在矢量 C++ 中可视化打印对象中的对象
- 使用 cout 打印对象指针值时地址长度不同
- C++模板打印对象名称
- 使用 c++ 中的重载运算符<<打印对象的动态数组