首先重载是不能做到的,相同函数参数类型前提下,不可能返回不同类型的返回值,但是想弄一些歪招实现这个效果
模板不算,因为模板会根据不同的输入参数类型生成不同的函数,就不是调用相同的函数了
然后自己强制转类型,类似 malloc
void* test(int i);
使用虚函数
- class base {
- public:
- virtual void print()
- {
- cout << "base\n";
- }
- };
-
- class father : public base {
- public:
- void print()
- {
- cout << "father\n";
- }
- };
-
- base* test(int i) {
- if (i == 1)
- return new father();
- else
- return new base();
- }
operator TypeName() 可以把一种类当另外一个类型用
- #include
- using namespace std;
-
- class Foo {
- public:
- operator bool() const {
- return true;
- }
- operator int() const {
- return 2;
- }
- operator string() const {
- return "string";
- }
- };
-
- int main(int argc, const char* argv[]) {
- Foo foo1;
- bool b = foo1;
- int i = foo1;
- string s = foo1;
-
- cout << b << endl;
- cout << i << endl;
- cout << s << endl;
- return 0;
- }
- /*
- * 输出
- 1
- 2
- string
- */
基于此原理,我们可以制作一个 test 函数,实现文章开头提到的功能
- #include
- using namespace std;
-
- class Foo {
- public:
- Foo(bool b1, int i1, string s1) {
- b = b1;
- i = i1;
- s = s1;
- }
- operator bool() const {
- return b;
- }
- operator int() const {
- return i;
- }
- operator string() const {
- return s;
- }
- bool b;
- int i;
- string s;
- };
- Foo test(bool b, int i, string s) {
- return Foo(b, i, s);
- }
- int main(int argc, const char* argv[]) {
-
- bool b = test(1, 2, "3");
- int i = test(1, 2, "3");
- string s = test(1, 2, "3");
-
- cout << b << endl;
- cout << i << endl;
- cout << s << endl;
- return 0;
- }
- /*
- * 输出
- 1
- 2
- 3
- */