在C ++中的函数定义中混合指针和引用 [英] Mixing pointers and references in function definition in C++

查看:119
本文介绍了在C ++中的函数定义中混合指针和引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,其中有两个类的实例作为参数:

I have a function that has two instances of classes as arguments:

void cookPasta(const Tomato& tomato, const Meat* meat)
{
    if (meat != nullptr)
        cookPastaWithMeat(tomato, *meat);
    else
        cookPastaWithoutMeat(tomato);
}

如函数所示,总是需要Tomato的实例,而Meat是可选的,而可以传递nullptr.我这样做是为了即使用户从未声明Meat类的实例,也可以调用cookPasta函数.

As the function shows, an instance of Tomato is always required, whereas Meat is optional and a nullptr can be passed instead. I do this to allow the cookPasta function to be called even if the user has never declared an instance of the Meat class.

在函数签名中混合引用和指针是不好的做法吗?

Is it bad practice to mix references and pointers in the function signature?

推荐答案

使用这种方法会丢失的一件事是有可能传入临时Meat,因为其地址无法使用.

The one thing you lose with this approach is the possibility to pass in a temporary Meat, as its address can't be taken.

为什么不通过简单地重命名cookPastaWithMeatcookPastaWithoutMeat来使用重载?

Why not use overloading, by simply renaming cookPastaWithMeat and cookPastaWithoutMeat ?

void cookPasta(const Tomato& tomato, const Meat& meat);
void cookPasta(const Tomato& tomato);

这篇关于在C ++中的函数定义中混合指针和引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆