C++对象切片错误是指在使用继承关系的类时,将派生类对象赋值给基类对象,导致派生类的特有成员被切掉,只保留了基类的部分成员。这通常是因为使用了对象的引用或指针来存储派生类对象,但将其赋值给基类对象的时候发生的错误。
问题举例
#include <iostream>
class Shape {
public:
virtual void draw() const {
std::cout << "Drawing a shape." << std::endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a circle." << std::endl;
}
void drawCircleOnly() const {
std::cout << "Drawing circle only." << std::endl;
}
};
int main() {
Circle circle;
Shape shape;
// 将派生类对象赋值给基类对象(对象切片)
shape = circle;
shape