cpp class4 ( test blog )
指针不安全性
-
fly pointer(null/right value; in func first use if(null); )
-
memory leak
-
return adr of local var(warning)
-
multi-pointers for one object!!!!!!!!!!
int main() {
int *p; //fly pointer 野指针
int i=10;
int j=20;
p = &i;
p = &j;
//可能和预想不同
//reference 引用(cpp new pointer)
int& r = i; //引用必须初始化,否则编译报错; r是i的引用(forever)
r = j; //不能表明引用改变,只能表示j赋值给r引用的对象
return 0;
}
value or address(pointer | reference)
read read/write
sizeof(object) sizeof(int)
copy-constructor nothing
reference:
void fun(int a) {
a++;
}
int main() {
int m = 10;
fun(m);
cout << m <<endl; //output still is 10
return 0;
}
// use reference
void fun(int& a) {
a++;
}
int main() {
int m = 10;
fun(m);
cout << m <<endl; //output is 11
return 0;
}
copy:
class Test {
int i; //value
int *j; //address handle
public:
//....
//copy construct
Test(Test& t);
/*
写一个private拷贝函数声明,卡编译
private:
Test(Test& t);
*/
}
//copy construct
Test::Test(Test& t) {
//default(bitwise copy)
this->i = t.i;
//this->j = t.j;
//deep copy addr(logic copy)
this->j = (int*) malloc(sizeof(int));
}
void func(int& a) {
}
int main() {
Test t1(1,2); //构造t1
Test t2(t1); //语法看起来不ok,但默认支持copy
//address变量 会指向同一个空间
//pass value, default use copy construct
//care about if defaut copy ?
}
一些琐碎:
//new & delete
int main() {
//no-use. without constructor
Test* a = (Test*)malloc(sizeof(Test));
//work
//(new = malloc(void*) + constructor(this))
//'new' is an operator(like +-*/)
Test *p = new Test();
//要同时构造多个,类必须支持默认构造(无参数)
Test *q = new Test[10];
//delete = destrucot + free
delete p;
delete []q;
return 0;
}
//const
class Test{
//...
void func() const;
//...
}
//...
void Test::func() const{
//...(read-only)
}
int func2(); //default const
//const pass by address
//约定只要不write 就 const
void fun(const Test *p) {
//p's value is read-only
}
int main() {
const Test t;
test.func(); //error,const object cannot use func
//unless: void func() const;
const double pi = 3.14;
int a = func2(); //work
func2()++; //error
}
tesst | tse | |
---|---|---|