C++笔记--赋值构造函数三种应用场景(3-1)
Posted xiangjai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++笔记--赋值构造函数三种应用场景(3-1)相关的知识,希望对你有一定的参考价值。
赋值构造函数三种应用场景
注:对象初始化操作 和 =等号操作 是两个不同的概念
类定义
class Student {
private:
int a;
public:
Student();
Student(int a);
Student(const Student &student);
~Student();
};
类实现
#include "Student.h"
#include "iostream"
using namespace std;
Student::Student() {
cout << "我是构造函数,自动被调用" << endl;
}
Student::Student(int a) {
this->a = a;
cout << "我是构造函数,自动被调用" << endl;
}
Student::Student(const Student &student) {
cout << "我是构造函数,我是通过另外一个对象student,来初始化自己" << endl;
}
Student::~Student() {
cout << "我是析构函数,自动被调用" << endl;
}
第一个应用场景
//单独搭建一个舞台
//对象初始化操作 和 =等号操作 是两个不同的概念
void scence1()
{
Student a1; //变量定义
//赋值构造函数的第一个应用场景
//我用对象1 初始化 对象2
Student a2 = a1; //定义变量并初始化
a2 = a1; //用a1来=号给a2 编译器给我们提供的浅copy
}
结果
我是构造函数,自动被调用
我是构造函数,我是通过另外一个对象student,来初始化自己
我是析构函数,自动被调用
我是析构函数,自动被调用
第二个应用场景
//单独搭建一个舞台
//对象初始化操作 和 =等号操作 是两个不同的概念
void scence2()
{
Student a1(10); //变量定义
//赋值构造函数的第一个应用场景
//我用对象1 初始化 对象2
Student a2(a1); //定义变量并初始化
a2 = a1; //用a1来=号给a2 编译器给我们提供的浅copy
}
结果
我是构造函数,自动被调用
我是构造函数,我是通过另外一个对象student,来初始化自己
我是析构函数,自动被调用
我是析构函数,自动被调用
第三个应用场景
Student scense3() {
Student s(1);
return s;
}
int main() {
Student student;
student = scense3();
cout << "student" << endl;
return 0;
}
以上是关于C++笔记--赋值构造函数三种应用场景(3-1)的主要内容,如果未能解决你的问题,请参考以下文章
c++复习笔记——右值引用(概念,使用场景),移动拷贝构造函数,赋值拷贝构造函数。
C++ Primer笔记14---chapter13 拷贝控制1