- 不通过“new”关键字,在栈上创建
- 通过关键字“new”,在堆上创建
两种方式的区别
在栈中的对象,其作用范围只是在函数内部,函数执行完成后就会调用析构函数,删除该对象。使用 “.” 而不是 “->” 调用对象的方法。
在堆中的对象,必须要程序员手动的去管理该对象的内存空间 。用运算符“->”调用对象的方法。new出来的对象必须用指针指明地址。
例子:
(1)无参构造函数:
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // 这是构造函数
private:
double length;
};
// 成员函数定义,包括构造函数
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
Line line;
// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
结果:
Object is being created Length of line : 6
(2)有参构造函数
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // 这是构造函数
private:
double length;
};
// 成员函数定义,包括构造函数
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
Line line(10.0);
// 获取默认设置的长度
cout << "Length of line : " << line.getLength() <<endl;
// 再次设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
结果:
Object is being created, length = 10 Length of line : 10 Length of line : 6
(3)new来创建
// 对于对象
class TestNew
{
private:
int ID;
public:
TestNew(int ID);
~TestNew();
};
TestNew::TestNew(int ID)
{
this->ID = ID;
}
TestNew::~TestNew()
{
std::cout<<"对象 "<<this->ID<<" 执行析构函数"<<std::endl;
delete ;
}
void Test()
{
TestNew test(1);//创建对象1,不使用new
TestNew *pTest = new TestNew(1);//创建对象2,使用new
delete pTest; // new的东西记得删除
}
int main()
{
Test();
}
结果:
再来一个例子
#include <iostream>
using namespace std;
class test {
public:
void print(int n) {
cout << "This is t" << n << "." << endl;
}
};
int main() {
test t1; //在栈(stack)上分配空间
test t2 = test(); //也是在栈(stack)上分配空间
test* t3 = new test(); //在堆(heap)上分配空间
test* t4; //只是声明,还没有分配空间
t1.print(1);
t2.print(2);
t3->print(3);
delete t3;
return 0;
}
This is t1.
This is t2.
This is t3.
现在总结一下静态对象
(1)全局静态对象在程序执行 main() 之前已经分配好存储空间 ,在 main() 执行完成后进行释放。
#include "fstream"
#include "string"
using namespace std;
void writeMessageToFile(const string& msg)
{
ofstream ofs;
ofs.open("test.txt", ios::app);
ofs << msg << endl<<endl;
ofs.close();
}
class TestClass
{
public:
TestClass() { writeMessageToFile( "TestClass() 执行");}
~TestClass(){ writeMessageToFile("~TestClass() 执行"); }
};
static TestClass test;
int main()
{
writeMessageToFile("main() 开始执行");
//
writeMessageToFile("main() 结束执行");
return 0;
}
(2)局部静态对象是从其所在函数第一次被调用时进行创建,直到整个程序结束才进行销毁;局部静态对象只有在第一次调用时进行初始化操作。
#include "iostream"
using namespace std;
int main()
{
for (int i = 0; i < 5; ++i)
{
static int s = 0;
s++;
cout << s << endl;
}
system("pause");
return 0;
}