在C++中,對象切片是指當一個派生類對象被賦值給一個基類對象時,派生類中的成員變量會被切掉,只剩下基類中的成員變量。為了避免對象切片,可以使用以下方法:
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
// ...
};
int main() {
Derived d;
Base* b = &d; // 使用指針
Base& r = d; // 使用引用
}
class Base {
public:
virtual ~Base() {}
virtual void foo() {}
};
class Derived : public Base {
public:
void foo() override {}
};
int main() {
Derived d;
Base* b = &d;
Derived* derived = dynamic_cast<Derived*>(b);
if (derived) {
derived->foo();
}
}
#include <vector>
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
// ...
};
int main() {
std::vector<Base*> vec;
vec.push_back(new Derived());
// ...
}
#include <memory>
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
// ...
};
int main() {
std::vector<std::shared_ptr<Base>> vec;
vec.push_back(std::make_shared<Derived>());
// ...
}
總之,要避免對象切片,關鍵是使用多態(tài)和智能指針,以及合理地設計類結構。