如何在一个函数中编写这3个成员函数定义?如果可能的话。你也可以expalain你是怎么做到的?。抱歉我不擅长英语而且不擅长编码请不要侮辱我。
void insert(int idx, PW* obj)
{
idx--;
double bd = summaryCost();
node x(1);
x.p = obj;
if (bd + obj->getCost() <= budget) {
if (idx <= vec.size()) {
vec.insert(vec.begin() + idx, x);
remain -= obj->getCost();
} else {
delete obj;
throw IndexOut();
}
} else {
delete obj;
throw DeficitError();
}
}
void insert(int idx, FW* obj) {
idx--;
double bd = summaryCost();
node x(2);
x.f = obj;
if (bd + obj->getCost() <= budget) {
if (idx <= vec.size()) {
vec.insert(vec.begin() + idx, x);
remain -= obj->getCost();
} else {
delete obj;
throw IndexOut();
}
} else {
delete obj;
throw DeficitError();
}
}
void insert(int idx, TW* obj) {
idx--;
double bd = summaryCost();
node x(3);
x.t = obj;
if (bd + obj->getCost() <= budget) {
if (idx <= vec.size()) {
vec.insert(vec.begin() + idx, x);
remain -= obj->getCost();
} else {
delete obj;
throw IndexOut();
}
} else {
delete obj;
throw DeficitError();
}
}
答案 0 :(得分:1)
如果PW
,FW
和TW
没有共同的基类,您可以使用特征类和模板。
完整示例:
// Empty types for illustration purposes.
struct PW {};
struct FW {};
struct TW {};
struct node
{
node(int i) {}
PW* p;
FW* f;
TW* t;
};
// For readability improvement.
template<typename T>
using member_ptr = T* node::*;
template<typename T>
struct NodeTraits {};
// Class-specific traits
template<>
struct NodeTraits<PW> {
enum {value = 1};
static member_ptr<PW> member;
};
template<>
struct NodeTraits<FW> {
enum {value = 2};
static member_ptr<FW> member;
};
template<>
struct NodeTraits<TW> {
enum {value = 3};
static member_ptr<TW> member;
};
member_ptr<PW> NodeTraits<PW>::member = &node::p;
member_ptr<FW> NodeTraits<FW>::member = &node::f;
member_ptr<TW> NodeTraits<TW>::member = &node::t;
// Finally, the function...
template<typename T>
void insert(int idx, T* obj)
{
node x(NodeTraits<T>::value);
member_ptr<T> ptr = NodeTraits<T>::member;
x.*ptr = obj;
// ...
}
// Using it...
int main()
{
PW p;
FW f;
TW t;
insert(0, &p);
insert(0, &f);
insert(0, &t);
}
解释为感兴趣的读者留下的练习。
答案 1 :(得分:0)
查看您的Dropbox代码,您似乎需要花费更多时间来研究虚拟功能和c ++纯虚函数;这可以让你做类似
的事情struct ChargeableItem {
virtual int getCost() = 0;
};
struct WorkItem : ChargeableItem {
virtual int getCost() {return 5;}
}
int total = 0;
void insert(ChargeableItem* i) {
total += i->getCost();
}
int main() {
WorkItem x;
insert(&x);
}
请注意上面的代码中有很多不良做法,但我认为这最终是你要做的。