【发布时间】:2019-04-09 21:18:07
【问题描述】:
我有多个类,每个类都有自己的方法。正如您在我的代码中看到的那样,所有这些方法都执行相同的任务。唯一独特的是在类中定义的title、code 和credit 成员的值。
有没有办法编写此代码,使得一组方法可以为每个类完成所需的任务(使用向方法发出请求的类中的特定值)?
我是一名大学生,因此我不想使用继承,因为我们还没有学会它。
class seng305
{
string title = "Software design and architecture", code = "SENG305";
int credit = 4;
public:
seng305();
~seng305();
string get_info();
string get_title();
int get_credit();
};
class comp219
{
string title = "Electronics in computer engineering", code = "COMP219";
int credit = 4;
public:
comp219();
~comp219();
string get_info();
string get_title();
int get_credit();
};
seng305::seng305()
{
cout << '\t' << "Created" << endl;
}
seng305::~seng305()
{
cout << '\t' << "Destroyed" << endl;
}
string seng305::get_info()
{
return (code + "-" + title);
}
string seng305::get_title()
{
return title;
}
int seng305::get_credit()
{
return credit;
}
//--------------------------------------------------
comp219::comp219()
{
cout << '\t' << "Created" << endl;
}
comp219::~comp219()
{
cout << '\t' << "Destroyed" << endl;
}
string comp219::get_info()
{
return (code + "-" + title);
}
string comp219::get_title()
{
return title;
}
int comp219::get_credit()
{
return credit;
}
如您所见,get_info()、get_title() 和 get_credit() 方法做同样的事情。
我想要一个get_info()、get_title()、get_credit() 能够完成每个班级的任务。
【问题讨论】:
-
你为什么不只使用一个类并用不同的数据创建它的实例?
-
将这些变量和函数分解为一个公共基类并从它继承? “我不想使用继承,因为我们还没有学会它。”这是一个非常愚蠢的限制。