拷贝构造函数

2016-06-18  本文已影响10人  LuckTime

拷贝构造函数

who where when what how
构造函数是什么:在类中和类使用相同的函数名的函数被称为构造函数

构造函数在哪里用:通常通过函数赋值参数给私有变量

构造函数什么时候用:1.使用类2.需要传递参数

构造函数怎么用?用来对创建的对象进行初始化。
特点:①:函数体本身不会返回东西,但还是会返回数值(可以理解为返回数值赋值参数,但函数体不返回什么),甚至连void都没有
②:与函数体同名。
③:不能直接调用,需要通过new运算符调用。或程序执行到它时调用
④:一个类只定义私有构造函数时,new不能调用。当一个类没定义构造函数时,c#自动调用构造函数、
引申:全局,静态构造函数,在main()函数之前就被调用了,局部构造函数在程序运行到那时,才被调用。。
关键点加黑(构造函数,主函数调用)
//==========================
//==========================
//==========================

include <iostream>

include <string>

using namespace std;

class Student{
private:
int age;
string name;
string room;
public :
Student(int age,string name,string ro) :age(age),name(name),room(ro){} //传递参数的构造函数
Student() {} //无参数构造函数
~Student(){} //调用析构函数

void show(){
cout << "My age is " <<age;
cout << " ,And I is " << name;
cout <<". an on the "<< room << " study!"<<endl;
}
};
int main(int argc, char* argv[])
{
Student S(18,"snow","1103"); //在主函数中的调用方法
S.show();
Student* s = NULL;
s = &S; //采用指针方法指向S,调用函数
s->show();
Student & SS =S; //引用需要初始化
SS.show();

}

上一篇下一篇

猜你喜欢

热点阅读