接受 class 和派生的 class 作为参数的函数
a Function that accepts both a class and a derived class as the argument
如何创建一个函数 F,它接受 class A 和派生自 A 的 class B 作为其唯一参数?
class A 和 class B 的构造函数和析构函数不同。
声明对 class 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
或者您可以为这两种类型的对象重载函数。
如何创建一个函数 F,它接受 class A 和派生自 A 的 class B 作为其唯一参数?
class A 和 class B 的构造函数和析构函数不同。
声明对 class 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
或者您可以为这两种类型的对象重载函数。