#include<iostream>
#include<Windows.h>
using namespace std;
class A {
float x, y;
public:
A(float a, float b) { x = a; y = b; cout << "调用了构造函数\n"; }
void Print() { cout << x << '\t' << y << endl; }
~A() { cout << "调用了析构函数\n"; }
};
void main()
{
cout << "进入main()函数\n";
A* pa1;
pa1 = new A(3.0, 5.0); //调用构造函数
pa1->Print();
delete pa1; //调用析构函数
cout << "退出main()函数\n";
}
运行结果:
·
·
·
2.
#include<iostream>
#include<Windows.h>
using namespace std;
class A {
float x, y;
public:
A(float a = 0, float b = 0) { x = a; y = b; cout << "调用了构造函数\n"; }
void Print(void) { cout << x << '\t' << y << endl; }
~A() { cout << "调用了析构函数\n"; }
};
void main(void)
{
A a1(1.0, 2.0);
A a2(a1); //调用拷贝构造函数,此处函数是系统默认的
A a3 = a1; //调用拷贝构造函数
a1.Print();
a2.Print();
a3.Print();
}
运行结果:
·
·
·
3.
#include<iostream>
#include<Windows.h>
using namespace std;
class A {
float x, y;
public:
A(float a, float b) { x = a; y = b; cout << "初始化自动局部对象\n"; }
A() { x = 0; y = 0; cout << "初始化静态局部对象\n"; }
A(float a) { x = a; y = 0; cout << "初始化全局对象\n"; }
void Print(void) { cout << x << '\t' << y << endl; }
};
A a0(100.0); //定义全局对象
void f() {
cout << " 进入f()函数\n";
A a2(1, 2);
static A a3; //初始化局部静态对象
}
void main() {
cout << "进入main函数\n";
A a1(3.0, 7.0);//定义局部自动对象
f(); f();
}
运行结果: