【问题标题】:Is it possible to use same functions for every class是否可以为每个班级使用相同的功能
【发布时间】:2019-04-09 21:18:07
【问题描述】:

我有多个类,每个类都有自己的方法。正如您在我的代码中看到的那样,所有这些方法都执行相同的任务。唯一独特的是在类中定义的titlecodecredit 成员的值。

有没有办法编写此代码,使得一组方法可以为每个类完成所需的任务(使用向方法发出请求的类中的特定值)?

我是一名大学生,因此我不想使用继承,因为我们还没有学会它。

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() 能够完成每个班级的任务。

【问题讨论】:

  • 你为什么不只使用一个类并用不同的数据创建它的实例?
  • 将这些变量和函数分解为一个公共基类并从它继承? “我不想使用继承,因为我们还没有学会它。”这是一个非常愚蠢的限制。

标签: c++ function class


【解决方案1】:

在这个例子中完全没有理由使用单独的类。一个类就足够了,例如:

class course
{
    string title, code;
    int credit;
public:
    course(const string &title, const string &code, int credit);
    ~course();
    string get_info() const;
    string get_title() const;
    int get_credit() const;
};

course::course(const string &title, const string &code, int credit)
    : title(title), code(code), credit(credit)
{
    cout << '\t' << "Created" << endl;
}

course::~course()
{
    cout << '\t' << "Destroyed" << endl;
}

string course::get_info() const
{
    return (code + "-" + title);
}

string course::get_title() const
{
    return title;
}

int course::get_credit() const
{
    return credit;
}

然后,您只需根据需要创建类的实例,例如:

course seng305("Software design and architecture", "SENG305", 4);
course comp219("Electronics in computer engineering", "COMP219", 4);
...

我知道你说过你不想使用继承,但这可能是下一个合乎逻辑的步骤,使用上面的代码作为基础:

class courseSeng305 : public course
{
public:
    courseSeng305() : course("Software design and architecture", "SENG305", 4) {}
};

class courseComp219 : public course
{
public:
    courseComp219() : course("Electronics in computer engineering", "COMP219", 4) {}
};

courseSeng305 seng305;
courseComp219 comp219;
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多