在 C++ 中,当参数的类型为父 class 时,如何调用子 class 的方法?
How to invoke a method an the child class when argument is of type parent class in C++?
我有以下代码(简化):
#include <cstdio>
class parent
{
public:
virtual void do_something() const
{
printf("hello I'm the parent class\n");
}
};
class child : public parent
{
public:
virtual void do_something() const
{
printf("hello I'm the child class\n");
}
};
void handle(parent p)
{
p.do_something();
}
int main()
{
child c;
handle(c);
return 0;
}
即使我传递了类型为 child
的参数,这也会打印 hello I'm the parent class
。我怎样才能告诉 C++ 表现得像 Java 那样并调用子方法,打印 hello I'm the child class
?
通过引用(或者,可能是 const 引用)接受参数:
void handle (parent & p)
// note this ^
{
p.do_something();
}
在你的情况下,slicing 发生了:child
的 parent
部分被提取为类型 parent
的单独对象并转到函数。
如果想把不同的子类放到一个集合中,通常的解决办法是使用智能指针,比如std::unique_ptr
or std::shared_ptr
.
我有以下代码(简化):
#include <cstdio>
class parent
{
public:
virtual void do_something() const
{
printf("hello I'm the parent class\n");
}
};
class child : public parent
{
public:
virtual void do_something() const
{
printf("hello I'm the child class\n");
}
};
void handle(parent p)
{
p.do_something();
}
int main()
{
child c;
handle(c);
return 0;
}
即使我传递了类型为 child
的参数,这也会打印 hello I'm the parent class
。我怎样才能告诉 C++ 表现得像 Java 那样并调用子方法,打印 hello I'm the child class
?
通过引用(或者,可能是 const 引用)接受参数:
void handle (parent & p)
// note this ^
{
p.do_something();
}
在你的情况下,slicing 发生了:child
的 parent
部分被提取为类型 parent
的单独对象并转到函数。
如果想把不同的子类放到一个集合中,通常的解决办法是使用智能指针,比如std::unique_ptr
or std::shared_ptr
.