【发布时间】: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<<重载。 编辑: 和成员初始化列表。 -
离题:
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