我只是想知道是否有办法做这样的事情:
Class A {}; //Base class
Class B : A {}; //B inherits from A
Class C : A {}; //C inherits from A
...
...
...
void func(B){do x;}
void func(C){do y;}
...
...
...
list<A> l //l contains Bs or Cs.
for each element in l {func(element);}
并获得每个人的预期行为?
答案 0 :(得分:2)
您可以执行以下操作:
class A // Base clss
{
public: // or protected, depends on your needs
virtual void func() {};
};
class B : public A //B inherits from A
{
public: // or protected, depends on your needs
void func() { do x };
};
class C : public A //C inherits from A
{
public: // or protected, depends on your needs
void func() { do y };
};
...
...
...
list<A*> l //l contains Bs or Cs.
for each element in l { element->func(); }
通过这种方式,您可以使用多态而不是重载静态函数func。
答案 1 :(得分:0)
#include <iostream>
#include <vector>
class A
{
public:
virtual void func() {}
};
class B : public A
{
public:
void func()
{
std::cout << "B prints x" << std::endl;
}
};
class C : public A
{
public:
void func()
{
std::cout << "C prints y" << std::endl;
}
};
int main()
{
std::vector<A*> v;
v.push_back(new B());
v.push_back(new C());
for (std::vector<A*>::iterator it = v.begin(); it != v.end(); ++it){
(*it)->func();
}
return 0;
}
输出:
B prints x
C prints y
答案 2 :(得分:0)
您可以使用多态性。例如
#include <iostream>
#include <memory>
#include <list>
#include <algorithm>
class A
{
public:
virtual ~A() {}
virtual void do_it() = 0;
};
class B : public A
{
public:
virtual void do_it() { std::cout << "processing of B\n"; };
};
class C : public A
{
public:
virtual void do_it() { std::cout << "processing of C\n"; };
};
void f( std::unique_ptr<A> &pa ) { pa->do_it(); }
int main()
{
std::list<std::unique_ptr<A>> l;
l.push_back( std::unique_ptr<A>( new B ) );
l.push_back( std::unique_ptr<A>( new C ) );
std::for_each( l.begin(), l.end(), f );
}