C++ 函数:在相同类型参数情况下返回不同类型值

首先重载是不能做到的,相同函数参数类型前提下,不可能返回不同类型的返回值,但是想弄一些歪招实现这个效果

模板不算,因为模板会根据不同的输入参数类型生成不同的函数,就不是调用相同的函数了

1、使用 void* 的返回值

然后自己强制转类型,类似 malloc

void* test(int i);

2、类似使用工厂模式

使用虚函数

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();
}

3、使用 operator TypeName()

operator TypeName() 可以把一种类当另外一个类型用

#include <iostream>
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 <iostream>
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
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值