函数参数,多态
function parameters, polymorphism
我有以下一段代码。我想知道是否有一种方法来修改foo(a a),以便调用它会产生如下面的注释代码中的结果,但没有重载。
class A {
public: virtual void print() { std::cout << "An"; } };
class B : public A {
public: virtual void print() { std:cout << "Bn"; }
};
void foo( A a ) { a.print(); } // How to modify this, so it chooses to use B's print()?
// void foo( B a ) { a.print(); } // now, this would work!
int main( void ) {
A a;
foo( a ); // prints A
B b;
foo(b); // prints A, but I want it to print B
}
这可能吗?如果不是,为什么?
必须通过引用(或指针,但这里不需要指针)接受实参,否则对象将被切片。
void foo(A& a) { a.print(); }
相关文章:
- 具有默认模板参数的多态类的模板推导失败
- 对具有不同参数数量的虚函数的多态调用
- C++ 中函数指针中的多态参数
- 在多态性中重新定义功能(虚拟),具有不同数量的参数
- 具有不同参数的多态性
- C 11多态映射键静态断言失败:哈希函数必须与密钥类型的参数无关
- C++传递函数作为具有多态类型的参数
- 为什么说C++不支持参数多态性
- 具有非类型模板参数的多态性
- 是否可以找出多态C++ 14 lambda 的参数类型和返回类型
- C++ 多态性和可变参数模板
- C++ 多态函数以 void * 和其他指针类型为参数:是否被认为是模棱两可的
- C++,多态性与函数参数的模板化
- 函数参数,多态
- 成员变量多态性和参数引用
- c++中具有不同参数的函数继承与多态
- c++对象参数:多态性,值语义,对象生命周期
- gtest类型参数化的多态性
- 具有可变函数参数的C++多态性
- 多态lambda的非类型模板参数