测试1 new/delete的使用原则
使用new/delete/new[]/delete[]的原则一般是成对使用,但是如果不成对会有什么结果呢
#include <stdlib.h>
#include <iostream>
using namespace std;
class tcbn
{
private:int id;
public:
tcbn(){ id = 0, cout << "init id= " << id << endl; }
~tcbn(){ cout << "des-init id= " << id << endl; }
};
int main()
{
int * a = new int[4];
delete a;
int * b = new int[4];
delete[] b;
tcbn * u = new tcbn[4];
delete[] u;
tcbn * t = new tcbn[4];
delete t; //运行到这一句报错
system("pause");
}
运行结果:
运行到最后一句的时候报错了
结论:
对于基础类型,delete[]和delete(最起码在效果上似乎)是一样的(但是内部到底是不是一样有待考证)
对于类,new和delete,new[]和delete[]要成对使用,否则可能报错
测试2:将类的构造函数声明为private
#include <stdlib.h>
#include <iostream>
using namespace std;
class tcbn
{
private:
int id;
tcbn(){ ; }
~tcbn(){ ; }
};
int main()
{
tcbn t1; //错误:不能访问
}
运行结果:不能编译成功,直接提示不能访问(看来构造函数放在private里不妥的)
但是有一个例外,就是,函数内部构造类,并留出个InitInstance()之类的接口,然后用指针的方式新建类,不知道这样是否可行(明天验证)
不用等明天了,今天就验证了——毫无意义!!
#include <stdlib.h>
#include <iostream>
using namespace std;
class tcbn
{
private:
int id;
tcbn(){ id=0; }
tcbn(int x1){ id = x1; }
~tcbn(){ ; }
public:
void init_one(){ tcbn T(17001); }
int get_id(){ return id; }
};
int main()
{
tcbn * t = (tcbn *)malloc(sizeof(tcbn));
t->init_one(); //很好但是毫无意义/(ㄒoㄒ)/~~
//cout<<t->get_id()<<endl; 注意这一行是不科学的
int a; cin >> a;
}
测试3,explicit的作用
explicit的作用是禁止隐式类型转换,示例代码如下:
#include <stdlib.h>
#include <iostream>
using namespace std;
class tcbn
{
private:
int id;
public:
int get_id(){ return id; }
tcbn() { id = 0, cout << "init for id= " << id << endl; }
tcbn(int x1) { id = x1, cout << "init for id= " << id << endl; }//这里可能会加上explicit 修饰
~tcbn(){ cout << "des-init for id= " << id << endl; }
};
int main()
{
{
//id=17001的类
cout << "----------test for 17001----------------\n";
tcbn tcb17001 = 17001;//输出 init for id 17001
cout << tcb17001.get_id() << endl;//输出17001
//id=18001的类
cout << "----------test for 18001----------------\n";
tcbn tcbn18001;//输出 init for id= 0
cout << "---\n";
//注意:下一句,如果在类的构造函数tcbn(int x1)前面加上explicit ,则下面这句话编译报错
tcbn18001 = 18001;//输出 init for id =18001和des-init for id=18001
cout << tcbn18001.get_id() << endl;//输出18001
//id=19001的类
cout << "----------test for 19001----------------\n";
tcbn tcbn19001(19001);//输出init for id=19001
tcbn tcbn19002;//输出init for id=0
tcbn19002 = tcbn19001;//无输出
cout << tcbn19002.get_id() << " " << tcbn19001.get_id() << endl;//输出19001 19001
}//输出19001,19001,18001,17001的析构
int a; cin >> a;
}
测试4 临时匿名对象
#include <stdlib.h>
#include <iostream>
using namespace std;
class tcbn
{
private:
int id;
public:
int get_id(){ return id; }
tcbn() { id = 0, cout << "init for id= " << id << endl; }
tcbn(int x1) { id = x1, cout << "init for id= " << id << endl; }
~tcbn(){ cout << "des-init for id= " << id << endl; }
};
int main()
{
cout << "["<<endl;
cout << tcbn(17001).get_id() << endl;
cout << "]" << endl;
int a; cin >> a;
}
输出为
[
init for id= 17001
17001
des-init for id= 17001
]
可见临时匿名对象的作用域是语句结束。