【问题标题】:a Function that accepts both a class and a derived class as the argument一个接受类和派生类作为参数的函数
【发布时间】:2017-01-08 06:44:50
【问题描述】:

如何使函数 F 同时接受一个类 A 和一个从 A 派生的类 B 作为其唯一参数?

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

【问题讨论】:

    标签: c++ class inheritance reference pass-by-reference


    【解决方案1】:

    将参数声明为对 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2017-11-08
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多