C++ 同时接受类和派生类作为参数的函数
如何使函数F的唯一参数同时接受类a和从类a派生的类BC++ 同时接受类和派生类作为参数的函数,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()
类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