数组的定义和初始化

一、定义

数组的维数必须用大于等于1的常量表达式来定义

整形字面值常量、枚举常量或者常量表达式初始化的整形const对象;

二、初始化

1、显示初始化数组元素

*在函数体外定义的内置数组,其元素均初始化为0;

*在函数体内定义的内置数组,其元素无初始化;

*不管数组在哪里定义,如果其元素为类类型,则自动调用该类的默认构造函数进行初始;如果该类没有默认构造函数,则必须为该数组的元素提供显示初始化

2、特殊的字符数组

3、不允许数组直接复制和赋值

// SHUZU.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using std::string;

int get_size()
{
    static int i = 0;
    i = i + 1;
    return i;
}

class testClass
{
public:
protected:
private:
    int a;
    char* p;
};

int atest[10];
testClass atc[10];

int _tmain(int argc, _TCHAR* argv[])
{
    const unsigned buf_size = 512, max_files = 20;
    int staff_size = 27;
    const unsigned sz = get_size();//sz是const对象,但是他的值要多运行时调用get_size才能知道
    char input_buffer[buf_size];//buf_size是const常量
    string fileTable[max_files + 1];//ok max_files是const常量,max_files + 1在编译时候就能算出是21
//     double salaries[staff_size];//error non const variable
//     int test_scores[get_size()];//error not const expression
//     int vals[sz];//error size not known until run time

    //显示初始化数组元素
    int btest[10];
    testClass btc[10];

    //特殊的字符数组
    char ca1[] = {'c', '+', '+'};//3维
    char ca2[] = {'c','+','+', ''};//4维
    char ca3[] = "c++";//4维 null terminator added automatically

    //不允许数组直接复制和赋值
    int ia[] = {0, 1, 2};
    //int ia2[](ia); //error 
    int ia3[];
    //ia3 = ia; //error
    return 0;
}

独到的、9

本文由博主(YinaPan)原创或者转载,如若转载请务必注明出处,谢谢合作!
原文地址:https://www.cnblogs.com/YinaPan/p/3889217.html