c++创建对象两个方式的疑问
/**
c++创建对象两个方式
ClassType 对象名;
ClassType *指针变量 = new ClassType
而且也在网上看了他们的区别
结果测试发现和看的不一样如下:
按理第一种创建方式在作用域之外就会调用析构函数销毁,为什么作用域之外还能使用,而且输入输出文件内容还是一样
/*
#include <iostream>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <ostream>
#define num 12700
//num定义为12700是因为再多栈空间就不够了
using namespace std;
class student {
public:
string name;
double a,b,c,d,e,f,g,h;
student() {
name.append(1,(char)rand());
}
// ~student(){
// //cout<<"destroy "<<name<<endl;
// }
};
class control {
public:
vector<student> all;
//ofstream addop("addop.txt"); 这里为什么不能作为成员变量
public:
void add(ofstream &addop) {
student arr[num];
for(int i=0;i<num;i++) {
arr[i].name.append("add");
if(i==0){cout<<arr[i].name<<endl;system("PAUSE");}
if(i==num-1){cout<<arr[i].name<<endl;system("PAUSE");}
all.push_back(arr[i]);
addop<<arr[i].name; //输出
}
}
void add2(ofstream &addop,control & con) {
student arr[num];
for(int i=0;i<num;i++) {
arr[i].name.append("add2");
all.push_back(arr[i]);
addop<<arr[i].name; //输出
}
}
};
int main()
{
ofstream addop("addop.txt");
ofstream itop("itop.txt");
control con;
con.add(addop);
cout<<"size add"<<con.all.size()<<endl;
system("PAUSE");
con.add2(addop,con);
cout<<"add 2 size"<<con.all.size()<<endl;
system("PAUSE");
vector<student>::iterator it = con.all.begin();
while(it!=con.all.end()) {
//cout<<it->name;
itop<<it->name;
it++;
}
addop.close();
itop.close();
return 0;
}
[解决办法]