相关疑难解决方法(0)

如何在C++中使用数组?

C++从C继承了数组,几乎无处不在.C++提供了易于使用且不易出错的抽象(std::vector<T>自C++ 98和C++ 11std::array<T, n>以来),因此对数组的需求并不像在C中那样频繁出现.但是,当您阅读遗产时代码或与用C编写的库交互,你应该牢牢掌握数组如何工作.

本FAQ分为五个部分:

  1. 类型级别的数组和访问元素
  2. 数组创建和初始化
  3. 赋值和参数传递
  4. 多维数组和指针数组
  5. 使用数组时常见的陷阱

如果您觉得此常见问题解答中缺少重要内容,请写下答案并将其作为附加部分链接到此处.

在下文中,"数组"表示"C数组",而不是类模板std::array.假定了C声明符语法的基本知识.请注意,面对异常,手动使用newdelete如下所示是非常危险的,但这是另一个常见问题解答的主题.

(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)

c++ arrays pointers c++-faq multidimensional-array

469
推荐指数
5
解决办法
12万
查看次数

在构造函数上指定constexpr会自动使从它创建的所有对象都是constexpr吗?

这是我的代码:

class test{
    public:
    constexpr test(){

    }

    constexpr int operator+(const test& rhs){
        return 1;
    }
};



int main(){

    test t;                         //constexpr word isn't necessary
    constexpr int b = t+test();     // works at compile time!


    int w = 10;                     // ERROR constexpr required
    constexpr int c = w + 2;        // Requires w to be constexpr
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我注意到即使我没有指定测试,它仍然有效constexpr.我尝试通过执行相同的方式复制结果,int但我得到错误.具体来说,它希望我的int w内心constexpr int c = w + 2;成为constexpr.从我第一次尝试使用test,它是否工作,因为我constexpr已经在构造函数上使用的原因?如果是这种情况,那么假设 …

c++ language-lawyer constexpr c++11

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

编译器无法执行 constexpr 表达式

我有这样的代码:

template<typename ... Args>
constexpr size_t get_init_size(Args ... args) {
    return sizeof...(Args);
}

template<typename ... Args>
constexpr auto make_generic_header(Args ... args) {
    constexpr size_t header_lenght = get_init_size(args...);
    return header_lenght;
}

constexpr auto create_ipv4_header() {
    constexpr auto x = make_generic_header(0b01, 0b10, 0b01);
    return x;
}
Run Code Online (Sandbox Code Playgroud)

我知道这是虚拟代码,但我将其隔离以查找错误。

编译器给我错误(GCC):

In instantiation of 'constexpr auto make_generic_header(Args&& ...) [with Args = {int, int, int}]':
/tmp/tmp.CaO5YHcqd8/network.h:39:43:   required from here
/tmp/tmp.CaO5YHcqd8/network.h:31:22: error: 'args#0' is not a constant expression
   31 |     constexpr size_t header_lenght = get_init_size(args...);
      |                      ^~~~~~~~~~~~~ …
Run Code Online (Sandbox Code Playgroud)

c++ templates constexpr c++17 constexpr-function

4
推荐指数
1
解决办法
616
查看次数