在C ++函数头中初始化变量 [英] Initializing variable in C++ function header

查看:142
本文介绍了在C ++函数头中初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



(这是位于中的函数原型, someCode.hpp

  void someFunction(const double& a,double& b,const double c = 0,const double * d = 0); 

(以下是位于 someCode.cpp #include someCode.hpp

  void someFunction(const double& a,double& b,const double c,const double * d); 

我可以使用以下方法合法调用 someFunction / p>

  someFunction(* ptr1,* ptr2); 

和/或

  someFunction(* ptr1,* ptr2,val1,& val2); 

变量 ptr1 ,<$ c已经适当定义了$ c> ptr2 , val val2 val1 val2 不等于零?为什么或为什么不是?



如果它是合法的,这个语法首选与重载一个函数来说明可选参数?

解决方案

是的,这是合法的,这叫做默认参数。我会说,由于涉及较少的代码,它是首选重载。



关于您对 const 的评论,那不适用于默认值本身,它适用于参数。如果你有一个类型为 const char * fruit =apple的参数,这并不意味着它必须用一个字符指针调用,该指针的值与apple字符串文字的地址(这很好,因为这很难保证)。它只是意味着它必须用一个指向常量字符的指针来调用,并告诉你被调用的函数不需要写入该内存,它只能从中读取。


I've come across some C++ code that looks like this (simplified for this post):

(Here's the function prototype located in someCode.hpp)

void someFunction(const double & a, double & b, const double c = 0, const double * d = 0);

(Here's the first line of the function body located in someCode.cpp that #include's someCode.hpp)

void someFunction(const double & a, double & b, const double c, const double * d);

Can I legally call someFunction using:

someFunction(*ptr1, *ptr2);

and/or

someFunction(*ptr1, *ptr2, val1, &val2);

where the variables ptr1, ptr2, val, and val2 have been defined appropriately and val1 and val2 do not equal zero? Why or why not?

And if it is legal, is this syntax preferred vs overloading a function to account for the optional parameters?

解决方案

Yes, this is legal, this is called default arguments. I would say it's preferred to overloading due to involving less code, yes.

Regarding your comment about const, that doesn't apply to the default value itself, it applies to the argument. If you have an argument of type const char* fruit = "apple", that doesn't mean it has to be called with a character pointer whose value is the same as the address of the "apple" string literal (which is good, since that would be hard to guarantee). It just means that it has to be called with a pointer to constant characters, and tells you that the function being called doesn't need to write to that memory, it is only read from.

这篇关于在C ++函数头中初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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