【问题标题】:Utilizing constructor, destructor, and printing off objects - c++利用构造函数、析构函数和打印对象 - C++
【发布时间】:2016-12-28 14:05:03
【问题描述】:

也阅读 cmets。

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

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

谢谢。

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

【问题讨论】:

  • 阅读operator&lt;&lt;重载。 编辑: 和成员初始化列表。
  • 离题:char newName 将是一个字符。在大多数文化中,这是一个相当短的名字。推荐查找std::string
  • 您不需要(不应该)编写一个空的用户定义的析构函数。编译器会为你生成它,它会是“微不足道的”,而你不会。如果您想明确一点,请将其声明为 ~NPC() = default; 参见 en.cppreference.com/w/cpp/language/destructor 。此外,您应该更喜欢初始化列表而不是构造函数主体。
  • 还阅读了Rules of Three, Five, and Zero。您会发现零规则与 @JesperJuhl 以及其他一些有用的指南具有相同的意义,如果不了解和观察其他三个和五个,您就无法进行有效的 C++ 编程。
  • 回到关于char newName的要点:在NPC bob("Bob",28, "Sword");"Bob"是一个const char *,一个指向不可修改的字符数组的指针,也就是一个字符串,而不是char,并且可以不能在这里使用。但不是std::string,尽管您无需任何努力即可将其转换为一个。强烈推荐doing some reading 并在继续之前完成一些练习。

标签: c++ class object constructor output


【解决方案1】:

将 char(只有一个字符)修复为 std::string。我添加了初始化列表和std::ostream &amp;operator &lt;&lt; 运算符。

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

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 2010-10-08
    • 2011-04-03
    • 2010-12-16
    • 2020-08-16
    • 1970-01-01
    • 2015-12-05
    • 2012-04-10
    • 2012-11-14
    相关资源
    最近更新 更多