利用构造函数、析构函数和打印对象- c++

Utilizing constructor, destructor, and printing off objects - c++

本文关键字:打印 对象 c++ 析构函数 构造函数      更新时间:2023-10-16

请阅读评论

基本上,我试图找出对象构造函数,析构函数和类。我创建了一个类,其中包含一些公共成员变量和一些私有成员变量。此时,我只在代码中使用了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 <<操作符。

http://en.cppreference.com/w/cpp/language/default_constructor

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