区别无参、带参、拷贝构造函数、赋值函数

来源:互联网 发布:nginx 防止ddos攻击 编辑:程序博客网 时间:2024/06/01 10:40
#include <iostream>
#include <string>
using namespace std;
struct Student//在结构体中
{
string name;
int age;
Student()   //无参构造函数
{
cout << "No-args Constructor" << endl;
age = -1;
name = "Unknown";
}
Student(string name, int age)//带参构造函数
{
cout << "Argumenting Constructor" << endl;
this->name = name;
this->age = age;
}
Student(const Student&other)//拷贝构造函数
{
cout << "Copy Constructor" << endl;
this->name = other.name;
this->age = other.age;
}
Student& operator=(const Student&other)//赋值函数
{
cout << "Assigning" << endl;
this->name = other.name;
this->age = other.age;
}
~Student()
{
cout << "Destructor" << endl;
}
friend ostream& operator<<(ostream & out, const Student&student)
{
cout << "Student[" << student.name << "]:" << "age=" << student.age;
return out;
}
};
int main()
{
Student student01;//调用了无参构造函数
cout << student01 << endl;
system("pause");

Student student02;//构造函数是被实例化过程中调用的,无论重载多少个构造函数,实际的只有一个
cout << student02 << endl;
system("pause");


Student student03 = Student();//不要误以为:等号右边调用了构造函数,然后赋值给左边又调用一次
cout << student03 << endl;//拷贝构造函数。其实只调用了构造函数,和Student student03;的效果一样
system("pause");


Student student04("LiMing", 1);//带参构造函数
cout << student04 << endl;
system("pause");


Student student05 = Student("LiMing", 1);//如上所说也是只调用一次带参构造函数
cout << student05 << endl;
system("pause");


Student student06 = student04;//拷贝构造函数,声明和赋值在同一行
cout << student06 << endl;
system("pause");


Student student07;//赋值函数,声明和赋值分开为两行
student07 = student04;
cout << student07 << endl;
system("pause");
return 0;
}
阅读全文
0 0
原创粉丝点击