使用基 class 类型指针指向派生类型对象
Usage of base class type pointer to the derived type object
假设我们有以下代码:
class Base
{
public:
virtual void print()
{
cout << "I'm base" << endl;
}
};
class Derived : public Base
{
public:
void print() override
{
cout << "I'm derived" << endl;
}
};
int main()
{
Base* b = new Derived();
b->print();
}
我无法理解的是:以这种方式而不是简单地创建对象有什么好处:
Derived* d = new Derived();
它是否仅在我们想要访问基class的字段和属性时使用,但对于虚函数使用派生class中的覆盖函数?
在您的特定代码中,使用第一种方法比使用第二种方法没有真正的好处。但是,考虑一下当您有两个(或更多)派生的 类 并且想要使用一个公共指针指向其中一个 类 的实例时,实际类型取决于某些(运行-时间)条件。这时候这种多态性就显示出它的用处了。
类似于以下内容:
int main()
{
Base* b;
std::cout << "Enter 1 or 2: ";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
b = new Derived1();
break;
case 2:
b = new Derived2();
break;
default:
b = new Base();
break;
}
b->print();
// ... other stuff to do with your polymorphic instance ...
delete b; // ... and don't forget to delete it when you're done!
return 0;
}
我将其保留为 'an exercise for the reader' 以提供 Derived1
和 Derived2
类.
的定义
假设我们有以下代码:
class Base
{
public:
virtual void print()
{
cout << "I'm base" << endl;
}
};
class Derived : public Base
{
public:
void print() override
{
cout << "I'm derived" << endl;
}
};
int main()
{
Base* b = new Derived();
b->print();
}
我无法理解的是:以这种方式而不是简单地创建对象有什么好处:
Derived* d = new Derived();
它是否仅在我们想要访问基class的字段和属性时使用,但对于虚函数使用派生class中的覆盖函数?
在您的特定代码中,使用第一种方法比使用第二种方法没有真正的好处。但是,考虑一下当您有两个(或更多)派生的 类 并且想要使用一个公共指针指向其中一个 类 的实例时,实际类型取决于某些(运行-时间)条件。这时候这种多态性就显示出它的用处了。
类似于以下内容:
int main()
{
Base* b;
std::cout << "Enter 1 or 2: ";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
b = new Derived1();
break;
case 2:
b = new Derived2();
break;
default:
b = new Base();
break;
}
b->print();
// ... other stuff to do with your polymorphic instance ...
delete b; // ... and don't forget to delete it when you're done!
return 0;
}
我将其保留为 'an exercise for the reader' 以提供 Derived1
和 Derived2
类.