对象切片(Object Slicing)是C++中常见的现象,发生在将派生类对象赋值给基类对象时
#include <iostream>
class Base {
public:
virtual void print() const {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void print() const override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Derived d;
Base* b = &d; // 使用指针避免对象切片
b->print(); // 输出 "Derived class"
return 0;
}
#include <iostream>
class Base {
public:
virtual void print() const {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void print() const override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Derived d;
Base* b = &d;
Derived* derivedPtr = dynamic_cast<Derived*>(b);
if (derivedPtr) {
derivedPtr->print(); // 输出 "Derived class"
} else {
std::cout << "Object slicing occurred" << std::endl;
}
return 0;
}
#include <iostream>
class Base {
public:
virtual void print() const {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void print() const override {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Derived d;
Base* b = &d;
b->print(); // 输出 "Derived class"
return 0;
}
总之,要检测和处理C++中的对象切片,可以使用指针或引用来保持多态性,使用dynamic_cast进行运行时类型检查,或者在基类中声明虚函数。