相关疑难解决方法(0)

方便的C++ struct初始化

我正在尝试找到一种方便的方法来初始化'pod'C++结构.现在,考虑以下结构:

struct FooBar {
  int foo;
  float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
Run Code Online (Sandbox Code Playgroud)

如果我想在C(!)中方便地初始化它,我可以简单地写:

/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
Run Code Online (Sandbox Code Playgroud)

请注意,我想明确地避免使用以下表示法,因为如果我将来更改结构中的任何内容,它会让我感到沮丧:

/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
Run Code Online (Sandbox Code Playgroud)

为了实现与/* A */示例中相同(或至少类似)的C++ ,我将不得不实现一个愚蠢的构造函数:

FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// -> …
Run Code Online (Sandbox Code Playgroud)

c++ struct initialization

137
推荐指数
6
解决办法
11万
查看次数

如何在C预处理器中使用#if在#define中?

我想编写一个宏,根据其参数的布尔值吐出代码.所以说DEF_CONST(true)应该扩展到const,并且DEF_CONST(false)应该扩展为无.

显然,以下方法不起作用,因为我们不能在#defines中使用另一个预处理器:

#define DEF_CONST(b_const) \
#if (b_const) \
  const \
#endif
Run Code Online (Sandbox Code Playgroud)

c c-preprocessor

46
推荐指数
2
解决办法
3万
查看次数

通过Struct和Class成员迭代

是否有可能在C++中迭代一个Struct或Class来查找它的所有成员?例如,如果我有struct a和b类:

struct a
{
  int a;
  int b;
  int c;
}

class b
{
  public:
    int a;
    int b;
  private:
    int c;
}
Run Code Online (Sandbox Code Playgroud)

是否可以循环它们以获得一个打印语句说"struct a has int named a,b,c"或"Class b has int named a,b,c"

c++ struct class

27
推荐指数
2
解决办法
3万
查看次数

C++ 遍历结构体的成员

说我有一个结构:

struct Boundary {
  int top;
  int left;
  int bottom;
  int right;
}
Run Code Online (Sandbox Code Playgroud)

和一个向量

std::vector<Boundary> boundaries;
Run Code Online (Sandbox Code Playgroud)

什么是最C ++风格的方式来访问结构得到的总和topleftbottomright分别?

我可以写一个循环

for (auto boundary: boundaries) {
  sum_top+=boundary.top;
  sum_bottom+=boundary.bottom;
  ...
}
Run Code Online (Sandbox Code Playgroud)

这似乎有很多重复。当然,我可以这样做:

std::vector<std::vector<int>> boundaries;

for (auto boundary: boundaries) {
  for(size_t i=0; i<boundary.size();i++) {
    sums.at(i)+=boundary.at(i)
  }
}
Run Code Online (Sandbox Code Playgroud)

但是后来我会丢失所有有意义的结构成员名称。有没有办法让我可以编写类似以下函数的内容:

sum_top=make_sum(boundaries,"top");
Run Code Online (Sandbox Code Playgroud)

反射似乎不是 C++ 中的一个选项。我愿意使用 C++ 到版本 14。

c++

7
推荐指数
2
解决办法
687
查看次数

在 C++ 中不使用字段名称打印实例化结构的值

我可以做吗?

例如,考虑以下结构:

struct bag {
     string fruit;
     string book;
     string money;
};
Run Code Online (Sandbox Code Playgroud)

我想以顺序形式打印结构包实例的字段值并获得如下输出:

apple
Computer Networking, A top-down Approach
100
Run Code Online (Sandbox Code Playgroud)

但不使用领域的名称(水果、书籍和金钱)。任何帮助,将不胜感激。我知道的唯一信息是所有字段都是 C++ 字符串。

c++ string struct

2
推荐指数
1
解决办法
1315
查看次数

标签 统计

c++ ×4

struct ×3

c ×1

c-preprocessor ×1

class ×1

initialization ×1

string ×1