C++函数不适用默认char参数。

huangapple go评论74阅读模式
英文:

C++ function not working properly with default char argument

问题

我有一段代码片段,其中声明了带有char和int类型默认参数的C++函数。

#include <iostream>

using namespace std;

int print(char c = '*', int num = 10);

int print(char c, int num)
{
    for (int i = 0; i < num; i++)
    {
        cout << c << endl;
    }
    cout << endl;
    return 0;
}

int main()
{
    int rep;
    char letter;

    cout << "Enter a character: ";
    cin >> letter;
    cout << "Enter the number of times it has to repeat: ";
    cin >> rep;

    print(letter, rep);

    print(rep);
    print(letter);

    return 0;
}

对于 print(rep); 没有输出,尽管给定了字符的默认参数。有任何想法为什么会发生这种情况吗?

我尝试使用默认参数,但char的默认参数不按预期工作,因此没有预期的字符输出。

英文:

I have a snippet of code where C++ functions are declared with default argument of char and int type.

#include &lt;iostream&gt;

using namespace std;

int print(char c = &#39;*&#39;, int num = 10);


int print(char c, int num)

{

	for (int i = 0; i &lt; num; i++)

	{

		cout &lt;&lt; c &lt;&lt; endl ;

	}

	cout &lt;&lt; endl;

	return 0;

}

int main()

{

	int rep;

	char letter;

	cout &lt;&lt; &quot;Enter a character : &quot;;

	cin &gt;&gt; letter;

	cout &lt;&lt; &quot;Enter the number of times it has to repeat : &quot;;

	cin &gt;&gt; rep;

	

	print(letter, rep);



	print(rep);

	print(letter);

	

	return 0;

}

There is no output for print(rep);

even though default argument for character is given. Any idea why this is happening?

I tried to use default arguments, but default argument of char is not working as intended and there is no intended character output for that.

答案1

得分: 2

参数仍然按顺序排列。只能省略末尾的参数。当你调用print(rep)时,整数会转换为char,并默认为num。如果你输入,比如说,值为“65”(表示‘A’的代码),你会注意到这一点。

英文:

Arguments are still in order. You can only omit arguments from the end. When you call print(rep), the integer gets converted to a char and num gets defaulted. You'll notice if you enter, say, "65" (the code for 'A') as the value for rep.

huangapple
  • 本文由 发表于 2023年3月3日 21:54:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定