C++ 函数重载 (参数分别为基类 派生类类型)
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
std::string getClearName(const char* name)
{
int status = -1;
char* clear_name = abi::__cxa_demangle(name, NULL, NULL, &status);
const char* demangle_name = (status==0) ? clear_name : name;
std::string ret_val(demangle_name);
free(clear_name);
return ret_val;
}
class A{
public:
int value;
A(int x):value(x){};
};
class B:public A{
public:
int base;
B(int x, int y):A(x),base(y){};
};
void print(A a){
std::cout << getClearName(typeid(a).name()) << std::endl;
std::cout << a.value << std::endl;
}
void print(B b){
std::cout << getClearName(typeid(b).name()) << std::endl;
std::cout << b.value << " " << b.base << std::endl;
}
int main(){
A a(1);
B b(1,2);
print(a);
print(b);
return 0;
}
# g++ Overload.cpp -o Overload
# ./Overload
A
1
B
1 2
如果去掉派生类函数
void print(B b){
std::cout << getClearName(typeid(b).name()) << std::endl;
std::cout << b.value << " " << b.base << std::endl;
}
那么
# g++ OverloadOne.cpp -o OverloadOne
# ./OverloadOne
A
1
A
1
|