同时接受类和派生类作为参数的函数

a Function that accepts both a class and a derived class as the argument

本文关键字:参数 函数 派生      更新时间:2023-10-16

如何使函数F既接受类a,又接受从a派生的类B,作为其唯一的参数?

类A和类B的构造函数和析构函数是不同的

将实参声明为a类对象的引用或const引用。

class A
{
    //...
};
class B : public A
{
    //...
};
void f( const A &a );

void f( const A *a );

或者像右值引用。

下面是一个示范程序

#include <iostream>
#include <string>
struct A
{
    virtual ~A() = default;
    A( const std::string &first ) : first( first ) {}
    virtual void who() { std::cout << first << std::endl; }
    std::string first;
};
struct B : A
{
    B( const std::string &first, const std::string &second ) : A( first ), second( second ) {}
    void who() { A::who(); std::cout << second << std::endl; }
    std::string second;
};
void f( A &&a )
{
    a.who();
}
int main() 
{
    f( A( "A" ) );
    f( B( "A", "B" ) );
    return 0;
}

输出为

A
A
B

或者可以为这两种类型的对象重载函数