Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 同时接受类和派生类作为参数的函数_C++_Class_Inheritance_Reference_Pass By Reference - Fatal编程技术网

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

C++ 同时接受类和派生类作为参数的函数,c++,class,inheritance,reference,pass-by-reference,C++,Class,Inheritance,Reference,Pass By Reference,如何使函数F的唯一参数同时接受类a和从类a派生的类B 类A和类B的构造函数和析构函数是不同的。将参数声明为类A的对象的引用或常量引用 class A { //... }; class B : public A { //... }; void f( const A &a ); 或 或者像右值引用 这是一个演示程序 #include <iostream> #include <string> struct A { virtual ~A()

如何使函数F的唯一参数同时接受类a和从类a派生的类B


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

将参数声明为类A的对象的引用或常量引用

class A
{
    //...
};

class B : public 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;
}
或者可以为这两种类型的对象重载函数

#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