【发布时间】:2016-06-29 00:29:38
【问题描述】:
是否可以根据实例化的派生类有不同的类型定义?
假设我有一个父类,它有一个虚函数 func()、两个 int 成员和一个 myType 类型的向量,以及两个共享相同 int 成员和向量的子类,但它们的实现是 @ 987654323@ 要求 myType 略有不同。
例如:
class Parent {
protected:
int myMember;
int myOtherMember;
std::vector<myType> vec;
public:
Parent(variable);
virtual int func() = 0;
}
class Child1 : public Parent {
private:
typedef <some type definiton> myType;
public:
Child1(variable) : Parent(variable){};
int func() {return someFunc();};
}
class Child2 : public Parent {
private:
typedef <some other type definiton> myType;
public:
Child2(variable) : Parent(variable){};
int func() {return someOtherFunc();};
}
我可以这样做吗?当我尝试过它时,它会在头文件中创建一个循环依赖,因为首先需要包含类Parent,但随后需要定义myType。
有没有办法根据班级向前声明myType?还是我只需要在每个类中包含一个不同的myType 向量,如下所示:
class Parent {
protected:
int myMember;
int myOtherMember;
public:
Parent(variable);
virtual int func() = 0;
}
class Child1 : public Parent {
private:
typedef <some type definiton> myType;
std::vector<myType> vec;
public:
Child1(variable) : Parent(variable){};
int func() {return someFunc();};
}
class Child2 : public Parent {
private:
typedef <some other type definiton> myType;
std::vector<myType> vec;
public:
Child2(variable) : Parent(variable){};
int func() {return someOtherFunc();};
}
【问题讨论】:
-
让它成为你父类的模板参数。
-
啊,谢谢,我完全忘记了模板,自从我用 c++ 做任何事情以来已经有几年了,我慢慢地记住了这一切..
标签: c++ typedef forward-declaration