假设我有一类人类类型,我想创建一个名为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;
}
答案 0 :(得分:0)
你应该关注一本好书(或者至少是一本好的在线教程);你的问题显示出对非常基本的C ++概念的困惑。
尽管如此,这里是您特定情况的答案(省略加载的详细信息和重要但不是针对此特定案例的概念)。 human
是类。类可以包含数据成员和成员函数。可以存在类类型的许多实例(或obejcts);每个都有自己的数据成员值。
每个成员函数都可以访问调用它的实例的成员(数据和函数)。它可以显式地(使用表示实例的指针的关键字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);
}