對象切片(Object Slicing)是C++中常見的現(xiàn)象,發(fā)生在將派生類對象賦值給基類對象時
#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++中的對象切片,可以使用指針或引用來保持多態(tài)性,使用dynamic_cast進行運行時類型檢查,或者在基類中聲明虛函數(shù)。