相关疑难解决方法(0)

初始化结构中的默认值

如果我只需要初始化C++结构的几个选择值,那么这是正确的:

struct foo {
    foo() : a(true), b(true) {}
    bool a;
    bool b;
    bool c;
 } bar;
Run Code Online (Sandbox Code Playgroud)

我是正确的假设我最终会与一个struct叫项bar的元素bar.a = true,bar.b = true和一个未定义的bar.c

c++

61
推荐指数
4
解决办法
13万
查看次数

重载决议:分配空括号

我写了一些代码S s;...... s = {};,期待它最终结果一样S s = {};.但事实并非如此.以下示例再现了该问题:

#include <iostream>

struct S
{
    S(): a(5) { }
    S(int t): a(t) {}

    S &operator=(int t)  { a = t; return *this; }
    S &operator=(S const &t) = default;

    int a;
};

int main()
{
    S s = {};

    S t;
    t = {};

    std::cout << s.a << '\n';
    std::cout << t.a << '\n';
}
Run Code Online (Sandbox Code Playgroud)

输出是:

5
0
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 为什么operator=(int)选择这里,而不是"模棱两可"或另一个?
  2. 是否有一个整洁的解决方法,没有改变S

我的意图是s …

c++ overload-resolution c++11

8
推荐指数
1
解决办法
589
查看次数

标签 统计

c++ ×2

c++11 ×1

overload-resolution ×1