当前位置:   article > 正文

【C++】构造函数_定义构造函数student(string name, course[] courses)初始化实例变

定义构造函数student(string name, course[] courses)初始化实例变量;

构造函数种类、作用

C++中的构造函数可以分为4类:默认构造函数、初始化构造函数、拷贝构造函数、移动构造函数。

默认构造函数和初始化构造函数。

在定义类的对象的时候,完成对象的初始化工作

class Student 
{ 
public:  
	//默认构造函数  
	Student()  
	{     
		num=1001;        
		age=18;      
	}  
	//初始化构造函数  
	Student(int n,int a):num(n),age(a){} 
private:  
		int num;  
		int age; 
	}; 
int main() 
{  
	//用默认构造函数初始化对象
	S1  Student s1;  
	//用初始化构造函数初始化对象
	S2  Student s2(1002,18);  
	return 0; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

有了有参的构造了,编译器就不提供默认的构造函数

拷贝构造函数
#include "stdafx.h" 
#include "iostream.h"  
class Test {     
	int i;     
	int *p; 
public:     
	Test(int ai,int value)     
	{         
		i = ai;         
		p = new int(value);     
	}     
	~Test()     
	{         
		delete p;     
	}     
	Test(const Test& t)     
	{         
		this->i = t.i;         
		this->p = new int(*t.p);     
	} 
}; //复制构造函数用于复制本类的对象 
int main(int argc, char* argv[]) 
{     
	Test t1(1,2);     
	Test t2(t1);//将对象t1复制给t2。注意复制和赋值的概念不同     
	return 0; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

赋值构造函数默认实现的是值拷贝(浅拷贝)。

移动构造函数

用于将其他类型的变量,隐式转换为本类对象。
下面的转换构造函数,将int类型的r转换为Student类型的对象,对象的age为r,num为1004.

Student(int r) 
{  
	int num=1004;  
	int age= r; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/244460
推荐阅读
相关标签
  

闽ICP备14008679号