C++从C继承了数组,几乎无处不在.C++提供了易于使用且不易出错的抽象(std::vector<T>自C++ 98和C++ 11std::array<T, n>以来),因此对数组的需求并不像在C中那样频繁出现.但是,当您阅读遗产时代码或与用C编写的库交互,你应该牢牢掌握数组如何工作.
本FAQ分为五个部分:
如果您觉得此常见问题解答中缺少重要内容,请写下答案并将其作为附加部分链接到此处.
在下文中,"数组"表示"C数组",而不是类模板std::array.假定了C声明符语法的基本知识.请注意,面对异常,手动使用new和delete如下所示是非常危险的,但这是另一个常见问题解答的主题.
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
这是我的代码:
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已经在构造函数上使用的原因?如果是这种情况,那么假设 …
我有这样的代码:
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)