类
构造方法
class Person{
public:
Person(){
cout << "无参构造函数调用" << endl;
}
Person(int p_age){
cout << "有参构造函数调用" << endl;
age = p_age;
};
// 析构函数 对象销毁的时候调用
~Person(){
cout << "析构函数调用" << endl;
};
// 拷贝构造函数
Person(const Person &p){
cout << "拷贝构造函数调用" << endl;
age = p.age;
}
int age;
};
// main 函数
int main()
{
// 类的构造函数
// 1.无参构造函数
Person p = Person();
p.age = 10;
cout << "p.age = " << p.age << endl;
// 2.有参构造函数
Person p2 = Person(2);
cout << "p2.age = " << p2.age << endl;
Person p4 = 100; // 相当于 Person p4 = Person(100);
cout << "p4.age = " << p4.age << endl;
// 3.拷贝构造函数
Person p1 = Person(p);
cout << "p1.age = " << p1.age << endl;
// 系统提供的拷贝构造函数
Person p3(p);
cout << "p3.age = " << p3.age << endl;
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}
公共方法和私有方法
class Circle
{
const double m_P = 3.14;
public: //公共权限
double calcZC()
{
return 2 * m_circle_r * m_P;
}
void setR(int r)
{
m_circle_r = r;
}
int m_circle_r;
void pn(){
cout << "调用公共函数" << endl;
}
private: // 私有权限
int getR(){
return m_circle_r;
}
};
// main 函数
int main()
{
Circle circle = Circle();
// circle.m_circle_r = 10;
circle.setR(20);
// int r = circle.getR(); // 无法调用私有方法
cout << "圆的周长:" << circle.calcZC() << endl;
circle.pn();
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}
深拷贝和浅拷贝
class Person{
public:
char * p_name;
int p_age;
Person(char * name,int age){
cout << "调用构造函数" << endl;
p_name = (char *)malloc(strlen(name)+1);
strcpy(p_name,name);
p_age = age;
}
Person(const Person &p){
cout << "调用构造函数" << endl;
p_name = (char *)malloc(strlen(p.p_name)+1);
p_age = p.p_age;
}
~Person(){
cout << "调用析构函数" << endl;
if(p_name != NULL){
free(p_name);
p_name = NULL;
}
}
};
// main 函数
int main()
{
// 浅拷贝 报错 析构函数会调用两次
// Person p1("hello",10);
// Person p2 (p1);
// 深拷贝 正常
Person p1((char *)"hello",10);
Person p2 (p1);
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}
注意
1.类对象作为成员变量的时候,先构造内部的类对象,再构造当前类对象;析构函数调用顺序相反。
2.关键字 explicit 防止隐式类型转换。
动态对象的创建和销毁
1.在C中申请内存malloc,销毁内存free,但是在C++中不同,代码如下:
class Student{
public:
Student(){
cout << "Student 构造方法" << endl;
}
~Student(){
cout << "Student 析构方法" << endl;
}
};
// main 函数
int main()
{
// 申请空间
Student * student = new Student;
// 释放空间
delete student;
// 打印结果
// Student 构造方法
// Student 析构方法
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}