通过引用设置 Bool 的默认值

发布于 2025-01-05 07:53:23 字数 345 浏览 2 评论 0原文

如何为作为引用的 bool 分配默认值?

我有一个这样的函数:

void someFunction(bool a = true, bool& b)
{
 if(a)
   b = false;
 else
   std::cout << "nothings changed" << std::endl;
}

在这种情况下我应该如何将默认值分配给 b ?

void someFunction(bool a = true, bool& b = false)

不会起作用。那么应该怎么做呢?

How do i assign a default value to a bool that is a reference?

I have a function like this :

void someFunction(bool a = true, bool& b)
{
 if(a)
   b = false;
 else
   std::cout << "nothings changed" << std::endl;
}

How should i assign the default value to b in this context?

void someFunction(bool a = true, bool& b = false)

will not work. So how should it be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寄风 2025-01-12 07:53:23

您不能使用值初始化非常量引用。你需要一个变量:

bool dummy_variable;

void someFunction(bool a = true, bool& b = dummy_variable)
{
    // ...
}

但是简单地返回 bool 可能会更有意义:

bool someFunction(bool a = true)
{
    return !a;
}

然后客户端仍然可以自己决定是否要忽略结果。

You cannot initialize non-const references with values. You need a variable:

bool dummy_variable;

void someFunction(bool a = true, bool& b = dummy_variable)
{
    // ...
}

But it would probably make a lot more sense to simply return the bool:

bool someFunction(bool a = true)
{
    return !a;
}

Then the client can still decide for himself if he wants to ignore the result or not.

厌倦 2025-01-12 07:53:23

您不能将临时对象绑定到非常量引用。您需要使用非临时对象:

bool bDefaultVal = false;

void someFunction(bool a = true, bool& b = bDefaultVal)
{
    ...
}

You cannot bound temporary object to a non-const reference. You need to use non-temp object:

bool bDefaultVal = false;

void someFunction(bool a = true, bool& b = bDefaultVal)
{
    ...
}
愚人国度 2025-01-12 07:53:23

为什么不使用指针呢?

#include <iostream>

using namespace std;

void someFunction(bool a = true, bool* b = nullptr)
{
    if (b != nullptr) {
        *b = a; 
    }
}

int main()
{
   bool res = true;
   someFunction();
   cout << res << endl; // true
   someFunction(false);
   cout << res << endl; // true
   someFunction(false, &res);
   cout << res << endl; // false

   return 0;
}

Why not use a pointer?

#include <iostream>

using namespace std;

void someFunction(bool a = true, bool* b = nullptr)
{
    if (b != nullptr) {
        *b = a; 
    }
}

int main()
{
   bool res = true;
   someFunction();
   cout << res << endl; // true
   someFunction(false);
   cout << res << endl; // true
   someFunction(false, &res);
   cout << res << endl; // false

   return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文