gpt4 book ai didi

c++ - 如何知道是否传递了可选函数参数还是使用默认函数参数?

转载 作者:行者123 更新时间:2023-12-02 04:12:48 24 4
gpt4 key购买 nike

void foo (  int arg1, int arg2)

foo(1)

foo(1,2)

我如何知道 int arg2 是否使用像第二个 foo 调用中那样传递的可选函数参数,或者像第一个 foo 中那样使用默认参数?

更新:

公开:

头文件

// Point 1
void fireworkShipment(stack<Firework*>&);
void sellFireworks(stack<Firework*>&, int quantity);

// Point 2
void metalShipment(stack<Metal>&);
~FireworkFactory();

// Point 3 for correctness, Point 4 for O(1) runtime
void sellFireworks(stack<Firework*>&, int quantity, Color color);
void sellFireworks(stack<Firework*>&, int quantity); //error here

cpp文件:

    void FireworkFactory::sellFireworks(stack<Firework*>& customerStack, int quantity, Color color){
// TODO
cout<< "which color: " << color << "\n";
for (int i = 0; i< fireworkstorage.size(); i++) {
if (fireworkstorage.front()->getColor() == color && quantity != 0) {
customerStack.push(fireworkstorage.front());
cout<< "Color: " <<fireworkstorage.front()->getColor() << "\n";
fireworkstorage.pop();
quantity--;
cout<< "Quantity: " <<quantity << "\n";
} else {
fireworkstorage.push(fireworkstorage.front());
fireworkstorage.pop();
}
}
}

void FireworkFactory::sellFireworks(stack<Firework*>& customerStack, int quantity){
for (int i = 0; i<quantity; i++) {
customerStack.push(fireworkstorage.front());
fireworkstorage.pop();
}
}

最佳答案

你不能。但是,您可以使用一个参数创建重载函数:

#include <iostream>

void awesome_function_with_default_parameters(int arg1, int arg2 = 42)
{
std::cout << "Doing some awesome work with " << arg1 << " and " << arg2 << std::endl;
}

void foo(int arg1, int arg2)
{
std::cout << "Both parameters passed" << std::endl;
awesome_function_with_default_parameters(arg1, arg2);
}

void foo(int arg1)
{
std::cout << "Only one parameter passed" << std::endl;
awesome_function_with_default_parameters(arg1);
}

int main()
{
foo(1);
foo(1, 314);
return 0;
}

关于c++ - 如何知道是否传递了可选函数参数还是使用默认函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35739474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com