C++ 复合类型

2018-01-01  本文已影响0人  zinclee123

本章主要讲的各种符合类型如数组、结构体、联合体等等,大学学过C语言,所以很多比较熟悉,所以本章还是记录一些比较容易遗漏、遗忘的细节。

1.数组
int cards[4] = {3,6,8,10};  //没问题
int hand[4];                //没问题
hand[4] = {5,6,7,8}         //不可以
hand = cards;               //不可以
short things[] = {1,2,3,4};
2.字符串
char dog[4] = {'a','b','c','d'};//不是字符串
char cat[4] = {'a','b','c','\0'};//是字符串
char bird[11] = "hahaha";//\0被自动填充了进去了
char fish[] = "bubbles";//让编译器计算数量
char b[10] = {'h','a','h','a','\0','h'};
std::cout << "blen=" << strlen(b) << std::endl;//输出4,strlen计算到第一个空字符为止
3.string类
4.结构体
struct inflatable{
    char name[20];
    float volume;
    double price;
};//以上是声明结构体类型

//以下是声明结构体变量
struct inflatable goose;//c语言,要求不能省略struct关键字
inflatable vincent;//c++可以省略struct关键字

/以下声明结构体数组
inflatable guests[2] = {
    {"Bambi",0.5,1999.91},
    {"Godzilla",2000,567.99}
};
5.共用体(联合体)
union one4all{
    int int_val;
    float float_val;
    double double_val;
};

int main() {
    using namespace std;
    one4all pail;
    pail.int_val = 4;
    cout << "pail.int_val = " << pail.int_val << endl;//输出pail.int_val = 4
    cout << "pail.float_val = " << pail.float_val << endl;//输出pail.float_val = 5.60519e-45,输出的数字是无意义的
    return 0;
}
struct widget{
    char brand[20];
    int type;
    union{
        long id_num;
        char id_chars[20];
    }
}
...
widget prize;
...
if(prize.type == 1){
    cin >> prize.id_num;
}else {
    cin >> prize.id_chars;
}

6.枚举
enum spectrum {red,orange,yellow,green,blue};//默认red=0,orange=1依次类推
enum spectrum {red,orange,yellow,green,blue};

int main() {
    using namespace std;
    spectrum band = red;
    ++band;
    cout << "band:" << band << endl;//报错:error: cannot increment expression of enum type 'spectrum'
    band = red + orange;
    cout << "band:" << band << endl;//报错:error: assigning to 'spectrum' from incompatible type 'int'
    return 0;
}
int color = blue;
band = 3;           //报错
color = 3 + red;    //没问题
enum bits {one =1,tow=2,four=4,eight=8};
enum bits2 {first ,second = 200,third};//third为201
7.指针和自由存储空间

这里只是简单介绍了指针,关于指针的种种会贯穿整本书,指针就是C/C+与Java/C#等其他高级语言的区别,大学毕业找工作的时候使劲看了一段时间指针,现在算是拾遗,本节内容比较简单,所以还是罗列一些小细节,对于对指针不熟悉的读者,建议着重看下这块。

int val = 10;
int *pt = &val;//pt为val对应的地址
int val2 = *pt;//val2等于10,将指针pt指向的值赋给val2
long *fellow;
*fellow = 23233;//fellow指向哪里没有明确,可能会引发一些古怪的问题,因为你修改了一块你也不知道在哪的内存的值
int *pt;
pt = 0xB8000000;//错误,编译器提示类型不匹配
pt = (int*)0xB8000000;//正确
//整形变量
int *ps = new int;
delete ps;
//整形数组
int *pss = new int[10];
delete [] pss;
int main() {
    using namespace std;
    int *pt = new int[10];
    int array[10];
    cout << "int size:" << sizeof(int) << endl;//输出为4
    cout << "pt size:" << sizeof(pt) << endl;//在我的MAC64位上输出8,32位机器应该是4
    cout << "array size:" << sizeof(array) << endl;//输出40
    delete [] pt;
    return 0;
}
8.数组的替代品
#include <vector>
...
using namespace std;
vector<int> vi;
int a[200];
a[-2] = 5;//非法
a[200] = 1;//非法,数组越界
a.at[200] = 1;//非法,程序将中断而不是继续运行下去

这篇总结就到这了,第四章说了不少概念,但都比较浅,后面会继续深入的。

上一篇 下一篇

猜你喜欢

热点阅读