C ++:直接在参数列表中使用数组文字的对象构造函数

时间:2016-04-06 16:09:59

标签: c++ arrays

我正在为我的程序编写全局常量,对我来说重要的是对象的数据尽可能本地化并且在一起,所以我想把所有内容放在构造函数中。

问题是,在这种情况下,常量是一个将其他对象数组作为参数的对象。

像这样的工作:

Constant::Constant(const char * string){...}
const Constant obj("string");

但是这样的事情不会:

Constant::Constant(const int * array){...}
const Constant obj({1, 2, 3, 4});

以及我需要的东西当然不会:

Constant::Constant(const vec2 * array){...}
const Constant obj({vec3(6, 9), vec3(4, 2)});

我是否尝试错误地执行此操作,使用错误的构造函数参数类型,或者字符串文字是可以像这样放在参数列表中的唯一数组文字?

1 个答案:

答案 0 :(得分:0)

除了评论中所说的内容之外,您可能还想尝试一下(实时查看here):

#include <bits/stdc++.h>

struct Stru {
  template <std::size_t n>
  explicit Stru(const int (&arr)[n]) {   
    for (int v : arr) {
      std::cout << v << ' ';
    }
  }
};

int main() {
  Stru obj({1, 2, 3});
}
相关问题