【问题标题】:class functions as pointers类函数作为指针
【发布时间】:2017-05-04 02:08:28
【问题描述】:

这些是我的头文件类函数:

public:
    hunter(string aSpecies);         // create a hunter of the given species
    void recordKills(string kill);   // add a new kill to the end of the hunter's list of kills
    string *theKills();              // return a pointer to the array of all kills by this hunter
    int numberOfKills();             // how many kills have been recorded

和类变量:

private:
    string kill;
    int numberkilled;
    string kills[20];

我不确定如何处理“字符串 *theKills()”

我尝试过这样做:

string hunter::*theKills(){
    pointer = kills;
    return pointer;
}

与 * 一样,它不会将 kills 识别为我的类变量的一部分,但我们应该使用相同的函数名称。

【问题讨论】:

  • 不应该是string* hunter::theKills(){吗?

标签: c++ class pointers inheritance


【解决方案1】:

语法如下:

<return type> <class name>::<function name>(<parameters>);

在你的情况下是:

  • &lt;return type&gt;string *
  • &lt;class name&gt;hunter
  • &lt;function name&gt;theKills
  • &lt;parameters&gt;:没有
string * hunter::theKills() {
    return kills; // you don't need a temporary pointer variable
}

为您省去使用指针的麻烦,我建议您使用 std::array 而不是 C 数组 string kills[20]

std::array<std::string, 20> kills;

请记住将const 限定符添加到每个不修改类的任何成员的成员函数。

我猜using namespace std; 的用法是bad practice

【讨论】:

  • std::array 和 C 数组有什么区别。也感谢您对您的冠军语法的帮助
  • 谢谢大佬,我知道这看起来很小,但非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2016-10-10
  • 2021-12-18
相关资源
最近更新 更多