/* * File: main.cpp * Author: Vicky * * Created on 2010年3月21日, 上午10:20 */ #include <iostream> using namespace std; // 无名联合块中的数据公用内存地址 void myswap(string &nn,string &mm){ cout<<"nn : " + nn<<"/t"<<"mm : " + mm<<endl; string temp; temp = nn; nn = mm; mm = temp; cout<<"nn : " + nn<<"/t"<<"mm : " + mm<<endl; } /* * */ int main() { // 无名联合,共享内存 union { /*定义一个联合*/ int i; int j; struct { /*在联合中定义一个结构*/ char first; char second; } half; }; i = 0x4241; /*联合成员赋值*/ half.first = 'a'; /*联合中结构成员赋值*/ half.second = 'b'; printf("%x/n", i); printf("%x/n", j); cout << half.first << endl; cout << half.second << endl; // getchar(); // 强制类型转换,C++的强制类型转换既可以使用Java方式,也可以使用ActionScript方式. float x = 12.083; // int y = x; 有时候报错,有时候不会,不规范! int y = (int) x; // int z = (int) x; int z = int(x); // double n = x; 有时候报错,有时候不会,不规范! double n = double(x); double m = (double) x; // double m = double(x); cout << x << endl; cout << y << endl; cout << z << endl; cout << n << endl; cout << m << endl; // C使用maloloc()和free()di/ongtai的分配内存和释放动态分配的内存,而C++使用new 和delte能更好,更简单的惊醒内存的分配和释放. int * p; // 声明一个整型指针变量. p = new int; * p = 10; cout << *p << endl; cout << sizeof (p) << endl; delete p; // type * p = new type; type 表示int,string等数据类型类型,new 称为为堆的一块自由存储区中为层序分配一块sizeof(type // 该内存的守地址被存放于指针p中.运算符delete用于释放new 分配的内存的首地址. int * o = new int; // * o = 99999; cout << sizeof (o) << endl; // 4 string * s = new string; // * s = "HelloWorld"; cout << sizeof (s) << endl; // 4 long * d = new long; * d = 1234567890; cout << sizeof (d) << endl; // 4 int * pi = new int[10]; // 创建数组 cout << sizeof (pi) << endl; // 4 int * pi2 = new int[20]; cout << sizeof (pi2) << endl; // 4 // 引用 string * k = new string; * k = "Test"; string * &k1 = k; string * k2 = new string("Test"); cout << k << endl; cout << k2 << endl; cout << (k == k2) << endl; // 1表示true cout << (k == k2) << endl; // 0表示false cout << &k << "/t" << &k1 << "/t" << &k2 << endl; // 查看内存地址 string h = "Test2"; string * h1 = &h; string &h2 = h; cout << *h1 << endl; cout << h2 << endl; cout<<(*h1==h2)<<endl; // 1 string nn = "Vicky"; string mm = "GOD"; myswap(nn,mm); return (EXIT_SUCCESS); }