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

时间:2016-08-22 06:17:06

标签: c++ class object constructor output

阅读评论。

基本上,我试图找出对象构造函数,析构函数和类。我创建了一个包含一些公共成员变量的类,以及一些私有成员变量。此时我只在我的代码中使用公共成员。

我的问题是,简单地说,我如何利用构造函数,析构函数以及将对象信息打印到控制台。

感谢。

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

1 个答案:

答案 0 :(得分:0)

修复了std :: string的char(只有一个字符)。我添加了初始化列表和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;
}
相关问题