假设我有一个人类类型的类,我想创建一个名为 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);
}