在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>());
// ...
}
总之,要避免对象切片,关键是使用多态和智能指针,以及合理地设计类结构。