new和delete运算符
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age)
{
cout << "Person的有参构造函数调用" << endl;
m_age = age;
}
Person(const Person &p)
{
cout << "Person的拷贝构造函数调用" << endl;
m_age = p.m_age;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
int m_age;
};
void test01()
{
Person *p2 = new Person;
Person *p3 = new Person(10);
Person *p4 = new Person(*p3);
delete p2;
delete p3;
delete p4;
}
void test02()
{
void * p = new Person;
delete p;
}
void test03()
{
Person* p = new Person[10];
delete [] p;
}
int main()
{
test03();
system("pause");
return 0;
}
静态成员
静态成员变量
#include<iostream>
using namespace std;
class Person
{
public:
int a;
static int b;
private:
static int c;
};
int Person::b = 10;
void test01()
{
Person p1;
Person p2;
Person p3;
cout << "p1:b" << p1.b << endl;
cout << "p2:b" << p2.b << endl;
cout << "p3:b" << p3.b << endl;
p3.b = 20;
cout << "p1:b" << p1.b << endl;
cout << "p2:b" << p2.b << endl;
cout << "p3:b" << p3.b << endl;
cout << "Person:b = " << Person::b << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
静态成员函数
#include<iostream>
using namespace std;
class Person
{
public:
int a;
static int b;
static void f()
{
d = 100;
cout << "静态成员函数调用" << endl;
}
static int d;
private:
static int c;
};
int Person::b = 10;
void test01()
{
Person p1;
Person p2;
Person p3;
cout << "p1:b" << p1.b << endl;
cout << "p2:b" << p2.b << endl;
cout << "p3:b" << p3.b << endl;
p3.b = 20;
cout << "p1:b" << p1.b << endl;
cout << "p2:b" << p2.b << endl;
cout << "p3:b" << p3.b << endl;
cout << "Person:b = " << Person::b << endl;
}
void test02()
{
Person p1;
p1.f();
Person::f();
}
int main()
{
test02();
system("pause");
return 0;
}