前言
构造函数的定义方式以及拷贝构造函数
一、构造函数
#include <iostream>
using namespace std;
class student
{
public:
int ag;
string nam;
student(int age, string name)
{
ag=age;
nam=name;
}
};//没加分号,记录丢人瞬间
以上是在类的内部以及构造函数内部初始化student类的对象的一些成员变量
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
int ag;
int nam;
student(int age, int name);
};
student::student(int age, int name):ag(age),nam(name)
{
cout << "构造函数的参数化列表" << endl;
}
以上是构造函数在类的外部定义以及使用参数化列表的形式给创建的对象的一些成员变量赋值
二、拷贝构造函数
什么时候会用到拷贝构造函数呢?当我们用一个对象给另外一个对象进行赋值的时候。
此时拷贝构造函数分为两种类型:一种是浅拷贝,另一种是深拷贝
如果我们不声明拷贝构造函数,那么编译器自己执行的拷贝构造函数是浅拷贝,但是浅拷贝只适用于类中没有动态数据成员的情况,当类里面有动态数据成员时就要使用深度拷贝。
#include<iostream>
using namespace std;
class A
{
public:
int a;
A(int b)
{
a = b;
cout << "有参构造" << endl;
}
A()
{
cout<<"无参构造"<<endl;
}
A(const A &B)
{
a = B.a;
cout<< "拷贝" << endl;
}
void fun()
{
int x;
}
};
void test()
{
A x;//无参构造不能使用括号,会被编译器认为是函数声明
A y(2);//括号调用有参构造
A z(y);//括号调用拷贝构造函数
}
int main()
{
test();
return 0;
}
总结
定义类的时候最后没加分号,编译器疯狂报错,“丢人”