抱歉,如果您之前已经提出并解决过此主题。
我想创建一个具有纯虚函数(抽象类)的基类,以便从该基类创建派生类时,用户必须在派生类中实现此函数的主体。关键是在纯虚函数中,我想将派生类型的对象作为参数对象。那可能吗 ?
例如:
class Base{
public:
virtual void DoSomething (A object1, B object2) = 0;
};
class A: public Base{
public:
DoSomething(A x, B y) {
...
...
};
};
class B: public Base{
public:
DoSomething(A x, B y) {
...
...
};
};
我尝试过,但是编译器抱怨说它对派生类一无所知,我理解,因为它们是在基类之后创建的。有办法规避吗?还是有另一种方法可以执行我想要的操作,即强制用户使用派生类类型的arguments arguments对象在派生类中实现函数的主体?
提前致谢 !
编辑:使用const引用的最终版本:-)
///Test-code. place anywhere in global C++ scope for testing
class A;
class B;
class Base{
public:
virtual void DoSomething ( const A & object1, const B & object2) = 0;
};
class A: public Base{
public:
void DoSomething(const A & object1, const B & object2) {
int i=0;
i++; //test break point
};
};
class B: public Base{
public:
void DoSomething(const A & object1, const B & object2) {
int i=0;
i++; //test break point
};
};
bool test()
{
A a;
B b;
a.DoSomething( A(), B() );
b.DoSomething( A(), B() );
return true;
}
static bool invokeTest = test();
///END of test-code
编辑:使用auto_ptr的更好的版本
///Test-code. place anywhere in global C++ scope for testing
#include <memory>
using std::auto_ptr;
class A;
class B;
class Base{
public:
virtual void DoSomething (auto_ptr<A> object1, auto_ptr<B> object2) = 0;
};
class A: public Base{
public:
void DoSomething(auto_ptr<A> x, auto_ptr<B> y) {
int i=0;
i++; //test break point
};
};
class B: public Base{
public:
void DoSomething(auto_ptr<A> x, auto_ptr<B> y) {
int i=0;
i++; //test break point
};
};
bool test()
{
Base *a = new A;
Base *b = new B;
a->DoSomething( auto_ptr<A>(new A), auto_ptr<B>(new B) );
b->DoSomething( auto_ptr<A>(new A), auto_ptr<B>(new B) );
return true;
}
static bool invokeTest = test();
///END of test-code
原始答案
如果参数是指针,则它应该起作用:
class A;
class B;
class Base{
public:
virtual void DoSomething (A * object1, B * object2) = 0;
};
class A: public Base{
public:
void DoSomething(A *x, B *y) {
};
};
class B: public Base{
public:
void DoSomething(A *x, B *y) {
};
};
PS:我不知道您为什么需要它?
PPS编辑:我仍然想知道为什么会需要它:-)?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句