1. 关于类的笔记
一个类应该这么写:
class thing{ //... };
结尾的分号VS会自己补上
然后是公有和私有部分
class thing{ private: //数据 public: //方法 };
对于数据部分,可以用枚举,也可以用静态整型来使用一个常量
//... private: static const int LEN = 20; enum {LEEN = 30}; int iarray[LEN]; char carray[LEEN]; //...
方法里除了自定义的方法之外,还可以写构造函数和析构函数。如果不写,就是使用隐式的默认函数
//... public: thing(){/*...*/} //默认构造函数 thing(const int & num, const char str[]); //带参数的构造函数,声明 ~thing(); //析构函数,没有参数 void foo(); //自定义的方法 thing bar(const thing & s); //返回类型为thing对象 //...
构造函数在创建函数时自动调用,析构函数在销毁对象时自动调用
既可以在创建函数时使用构造函数,也可以在之后再次调用构造函数
// main(){... thing A; //使用了默认构造函数 thing B(2,"Bit"); //使用了另一个构造函数 A = thing(1,"Alpha"); //重新使用了构造函数,改变了A thing *C = new thing(3,"Cobalt"); //动态对象使用构造函数 //...
写方法的时候要带上::符号说明隶属关系
//在文件中 thing::thing(const int & num=0, const char str[]="None") //默认参数只能写一次,不能在类里写了在这里又写 { iarray[0]=num; //编译器会知道这是thing类的变量 aarray=str; //不需要return } void thing::foo() //由于不是构造函数,必须写类型 { //... }
可以用this指针指代当前对象本身
thing thing::bar(const thing & s) { if(iarray[0]>s.iarray[0]) //可以看到,iarray是不需要this的,编译器会知道这是当前对象的iarray return s; else return *this; }
如果当前对象是const的,那么能使用的方法也只能是const的,此时这个方法确保不修改对象。
//class thing {... public: //... 之前的方法 void show()const; //在括号后添加const //...}; void thing::show()const { //std::cout << ... ; 另,不可以修改对象,例如aarray="newstring";无法通过 } //main() {... const thing D = thing(4,"Dritrot"); //显式调用构造函数 //D.foo(); 不可用 D.show(); //可用 //...
可以使用对象数组
//main() {... thing E[5]={ thing(51,"Empria"), //声明时使用构造函数 thing(52,"Elytra") //不必写满 };
2. 一些和类无关的笔记
论typedef的意义:
typedef unsigned long Item //... Item F[6];
在这之后通过修改typedef的源类型就可以修改Item的类型。这里的unsigned long就好似const int LEN=20的20,是一个根据需要修改的变值。
string的基础用法
string a = "as", b = "df"; cout << a + b; cin >> a >> b; a.swap(b); cout << a << b;
自己尝试即可~