class Point
{
public:
void init(int x, int y);
void print() const;
void move(int dx, int dy);
private:
int x;
int y;
};
Point a; //内存找了一个地方,放Point的对象 (对象搬进内存,C++不会将屋子打扫干净(成员变量值赋值0),原因是为了效率. a的成员变量值不确定)
a.init(1,2);
a.move(2,2);
a.print();
//visual studio编译debug: 对象里填充一种东西,表示屋子还没有被初
//始化过,填充0xcd. 当2个0xcd连在一起的时候,恰好是”烫”. 没有初
//始化的内存.
//visual studio: 足迹分析. 没有初始化的内存是0xcd, 初始化的内存就
//不是0xcd.
构造函数
class X
{
public:
int i;
X();//构造函数,对象创建的时候,自动被调用.
}
#include <stdio.h>
class A
{
public:
int i;
A();
void f();
};
A::A() //构造函数
{
i = 0;
printf("A::A()--this = %p\n",this);
}
void A::f()
{
this->i = 20;
printf("A::f()--&i=%p\n",&i);
printf("this = %p\n",this);
}
int main()
{
A a; //自动调构造函数 A::A()--this = 0xbff1cc58
A aa; //自动调构造函数 A::A()--this = 0xbff1cc50
a.i = 10;
printf("&a = %p\n",&a); //&a = 0xbff1cc58
printf("&a.i = %p\n",&(a.i)); &a = 0xbff1cc58
a.f(); //A::f()--&i= 0xbff1cc58, this = 0xbff1cc58
printf("&aa = %p\n", &aa); //&aa = 0xbff1cc50
aa.f(); //A::f()--&i= 0xbff1cc50, this = 0xbff1cc50
}
构造函数可以允许有参数,
class Tree
{
public:
Tree(int i);
}
int main()
{
Tree t(12);//调构造函数,12传给i
}
#include <iostream>
using namespace std;
class Tree
{
int height;
public:
Tree(int initialHeight);//构造函数
~Tree(); //析构函数
void grow(int years);
void printsize();
};
Tree::Tree(int initialHeight) //构造函数
{
height = initialHeight;
cout << "inside Tree::Tree()" << endl;
}
~Tree::Tree()
{
cout << "inside Tree destructor" << endl;
printsize();
}
void Tress::grow(int yeara)
{
height += years;
}
void Tree::printsize()
{
cout << "Tree height is " << height << endl;
}
int main()
{
cout << "before opening brace" << endl;//before opening brace
//{ 之前t不存在
{
Tree t(12); //inside Tree::Tree() 调构造函数
cout << "after Tree creation" << endl; // after Tree creation
t.printsize(); // Tree height is 12
t.grow(4);
cout << "before closing brace" << endl; // before closing brace
//inside Tree destructor 调析构函数
//Tree height is 16
}
//}之后t也不存在
cout << "after closing brace" << endl; //after closing brace
return 0;
}
析构函数
函数被消灭的时候调用.
class Y
{
public:
Y(); //构造函数
~Y();//析构函数
}
析构函数: 对象存在过程中,申请了一些资源. 用析构函数将申请的资源全部释放.