C++继承,重写时仍然调用基函数
我有以下两个类,一个类继承另一个类
Class A{
void print(){cout << "A" << endl;}
}
Class B : A{
void print(){cout << "B" << endl;}
}
Class C : A{
void print(){cout << "C" << endl;}
}
然后在另一个类中我有以下内容:
vector<A> things;
if (..)
things.push_back(C());
else if (..)
things.push_back(B());
things[0].print();
这总是打印 A
我希望它根据我添加到向量中的内容来打印 B 或 C
我该怎么做?
我尝试过抽象,但我不完全确定如何在 C++ 中使用它,而且它对我不起作用
I have the following two classes, one inherits from the other
Class A{
void print(){cout << "A" << endl;}
}
Class B : A{
void print(){cout << "B" << endl;}
}
Class C : A{
void print(){cout << "C" << endl;}
}
Then in another class I have the following:
vector<A> things;
if (..)
things.push_back(C());
else if (..)
things.push_back(B());
things[0].print();
this always prints A
I'd like it to print B or C depending on which thing I've added to the vector
how do I do this?
I've tried abstraction but I'm not entirely sure how to use it in C++ and it hasn't been working for me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如前所述,您需要虚拟函数来启用多态行为,并且不能直接按值在向量中存储类。
当您使用
std::vector
时,您将按值存储,因此您添加的对象(例如通过push_back()
)将被复制到一个实例A
,这意味着您丢失了对象的派生部分。此问题称为对象切片。正如已经建议的,您可以通过存储指向基类的指针(或智能指针)来避免这种情况,因此只有指针被复制到
向量
中:As mentioned, you need
virtual
functions to enable polymorphic behaviour and can't store classes directly by value in thevector
.When you use a
std::vector<A>
, you are storing by value and thus objects that you add, e.g. viapush_back()
are copied to an instance of anA
, which means you lose the derived part of the objects. This problem is known as object slicing.As already suggested you can avoid that by storing pointers (or smart pointers) to the base class, so only pointers are copied into the
vector
:1) 您需要在 A 类中将 print() 声明为虚拟。
2) 您的向量不正确——您不能在其中存储实际的 A 类对象;您将需要存储指向它们的指针以获得正确的行为(并且您必须稍后清理它们)和/或使用诸如 boost::shared_ptr 之类的东西。
1) You need to declare print() as virtual in class A.
2) Your vector is incorrect -- you can't store actual class A objects in there; you will need to store pointers to them for the correct behavior (and you will have to clean up after them later) and/or use something like a boost::shared_ptr.
您需要在基类中声明 virtual 函数,在本例中为类 a:
即使您没有在其中编写 virtual (但您可以),其他类也会选择该函数。
Virtual 告诉编译器该函数可以被覆盖。当您不使用虚拟时,它称为隐藏,并且工作方式不同,正如您所发现的。
You need to declare the function virtual in your base class, in this case that's class a:
The other classes will pick this up even if you don't write virtual in those (but you can).
Virtual tells the compiler that the function could be overridden. When you don't use virtual, it's called hiding and works differently, as you've found.