具有参数和比较的 C++ 类

标签 c++ class

<分区>

假设我有一个人类类型的类,我想创建一个名为 jim.punch(billy) 的方法函数;我创造了吉姆,我创造了比利。我在编写函数时如何引用 jim?让我们说任何返回都是基于他们的体重。所以如果比利更大,就会发生一些事情,如果吉姆更大,就会发生其他事情。我只是不知道如何在函数中使用 jim

#include <iostream>
using namespace std;

  class dog
 {
public:
     int age;
     int weight;
     int height;

     int punch(int);
  };

   int jim::punch(x)
   {
      if (jim > x) <------------------
      {
          return //something
      }  
      else
     {
         return something
    }

 int main()
 {
 human jim;
 jim.age = 30";
 jim.weight = 175;
 jim.height = 6;
 human billy; //etc 

 jim.punch(billy);

return 0;
}

最佳答案

你真的应该遵循一本好书(或者至少是一个好的在线教程);你的问题表明对非常基本的 C++ 概念感到困惑。

不过,这里是针对您的特定情况的答案(省略了负载的细节和重要但不适用于此特定情况的概念)。 human 是一个类。类可以有数据成员和成员函数。类类型的许多实例(或对象)可以存在;其中每一个都有自己的数据成员值。

每个成员函数都可以访问调用它的实例的成员(数据和函数)。它可以显式地(使用代表指向实例的指针的关键字 this)或隐式地(仅命名数据成员)这样做。

下面是您可以如何用代码表达您的情况:

class human
{
  //place data members such as age, height, weight here

public:
  int punch(const human &target);
};

int human::punch(const human &target)
{
  std::cout << "PUNCH!";

  if (weight > target.weight) //equivalent to this->weight > target.weight
  {
    return /* something which represents this object winning */
  }
  else
  {
    return /* something which represents target object winning */
  }
  //Note: you should handle == case as well
}


int main()
{
  human jim, billy;
  jim.punch(billy);
}

关于具有参数和比较的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21376374/

相关文章:

php - 无法将命名空间路径评估为变量

c++ - 如何通过子类型列表创建指针 vector ?

c++ - 快速 SSE 射线 - 4 个三角形相交

c++ - GLEW 未知类型名称

python - 如何使用类来使用变量调用对象?

html - 如何将此表格和按钮放在图像旁边(图像右侧)

python - 我需要类方面的帮助 - 用于显示文件名、文件大小、路径和其他任何内容的类

c++ - 通过引用传递 vector 的尾递归

c++ - 从 __m128i 中查找最小值/最大值

c++ - 类名未声明类型 C++