我想创建一个具有成员函数(例如。giveCharity)的类(例如Person),但我希望该方法的内容对于类的每个实例都是不同的,模仿人工智能。这可能吗?何时以及如何填充每个实例方法的代码?类方法对于类的每个实例都有不同的代码吗?
下面是一个例子:
public class Person
{
// data members
private int myNumOfKids;
private int myIncome;
private int myCash;
// constructor
public Person(int kids, int income, int cash)
{
myNumOfKids = kids;
myIncome = income;
myCash = cash;
}
// member function in question
public int giveCharity(Person friend)
{
int myCharity;
// This is where I want to input different code for each person
// that determines how much charity they will give their friend
// based on their friend's info (kids, income, cash, etc...),
// as well as their own tendency for compassion.
myCash -= myCharity;
return myCharity;
}
}
Person John = new Person(0, 35000, 500);
Person Gary = new Person(3, 40000, 100);
// John gives Gary some charity
Gary.myCash += John.giveCharity(Gary);
您的意思是,为操作添加一些变化?那么,你总是可以初始化一些参数,比如在构造函数中用随机值同情。 –