constructor:构造函数
destructor:析构函数
class X{
int i;
public:
X();//构造函数与类名相同,没有返回值,在对象被创建时自动被调用,构造函数也是成员函数
};
void f() {
X a;//只要对象被定义,构造函数就会被调用,即此时一定会发生a.X();
}
class Point {//C++的类不负责自动初始话
public:
void init(int x,int y);//初始化函数,如果不初始化,x,y的内容是什么不确定,并不一定是0
void print() const;
void move(int dx,int dy);
private:
int x;
int y;
};
Point a;
a.init(1,2);
a.move(2,2);
a.print();
class X{
int i;
public:
X();//构造函数与类名相同,没有返回值,在对象被创建时自动被调用,构造函数也是成员函数
};
void f() {
X a;//只要对象被定义,构造函数就会被调用,即此时一定会发生a.X();
}
class A{
public:
int i;
A();
~A();
void f();
};
struct B{
int i;
};
A::A(){
i=0;//构造函数也是成员函数,因此,构造函数使用的i也是this->i
printf("A::A()--this=%p\n",this);\\输出this的地址
}
A::~A(){
print("A::~A()\n");
}
voif d A::f(){
this->i=20;
printf("A::f()--&i=%p\n",&i);
printf("this=%p\n",this);
}
void f(struct B* p){
p->i=20;
}
int main(){
A a;
A aa;
B b;
a.i=10;
printf("&a=%p\n",&a);
printf("&a.i=%p\n",&(a.i));
a.f();
a.ff();
printf("&aa=%p\n",&aa);
}//离开mian时两个对象调用析构函数
//构造函数可以有参数
Tree(int i){
......
}
Tree t(12);//12会被传给i
#include<iostream>
using namespace std;
class Tree {
int height;
public:
Tree(int initialHeight); //Constructor
~Tree(); //Destructor
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 Tree::grow(int years) {
height+=years;
}
void Tree::printsize() {
cout<<"Tree height is "<<height<<endl;
}
void Tree::printsize(){
cout<<"Tree height is "<<height<<endl;
}
int main(){
cout<<"before opening brace"<<endl;
{//进入大括号前t不存在,离开大括号后t也不存在
Tree t(12);//进入大括号后,t才存在,才会调用构造函数
cout<<"after Tree creation"<<endl;
t.printsize();
t.grow(4);
cout<<"before close brace"<<endl;
}//此时调用析构函数
cout<<"after closing brace"<<endl;
}
class Y {
public:
~Y();//当对象要被消灭掉时调用析构函数,析构函数没有参数,析构完后释放资源
};