第二周学习:复制构造函数copy

概念

  1. 只有一个参数,即同类对象的引用
  2. X::X(X&)X::X(const X&) 常引用更常用
  3. 系统会生成默认复制构造函数,完成浅复制功能
  4. 若自己定义复制构造函数,则默认那个就没得了

起作用的三种情况

  1. 当用一个对象去初始化另一个对象
    classname object1(object2)
    classname object1 = object2 这是初始化语句,不是赋值
  2. 参数是类A的对象,invoking时,则类A的复制构造函数将被调用
    void func(A a1),所有类对象都要被初始化,这个初始化时将调用copy constructor function(开销会比较大,所以一般考虑常量引用参数
  3. 返回值是类A对象,则返回时复制构造函数被调用。

ATTENDTION

  1. 对象间赋值并不导致复制构造函数调用(若不是初始化就是赋值)

Example

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class student
{
    
    
	private:
		string name;
		char* hobby;
		int age;
	public:
		student(string n="no",char h[]=nullptr,int a=0);
		student(const student& s);
		~student();
		void displace();
 } ;
 
 student::student(string n,char h[],int a):name(n),age(a)
 {
    
    
 	hobby = new char[strlen(h)+1];
 	strcpy(hobby,h);
 }
 
 student::student(const student& s):name(s.name),age(s.age)
 {
    
    
 	hobby = new char[strlen(s.hobby)+1];
 	strcpy(hobby,s.hobby);
 }
 
 student::~student()
 {
    
    
 	delete [] hobby;
 }
 
 void student::displace()
 {
    
    
 	cout<<name<<" is "<<age<<" years old and good at "
 	<<hobby<<endl;
 }
 
 int main()
 {
    
    
 	student s2("Jeff","studying",20),s3("Alice","talking",18)
 	,s1=s2;
 	s2.displace();
 	s3.displace();
 	cout<<"S1 as followed: "<<endl;
 	s1.displace();
 }

ps.如果有动态分配内存的,一定要析构函数delete

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108551257
今日推荐