类里面的构造函数怎么写?

来源:百度知道 编辑:UC知道 时间:2024/05/04 16:35:34
有没有什么通法来编写自定义类的构造函数?
类型肯定是VOID
名字和类名字一样
就是形参怎么写?
函数语句体呢?
最好举个例子吧.
不然也不好回答.
c++

构造函数一般是用来进行初试化的,看你需要对哪些属性进行初始化
#include<iostream.h>
#include<string.h>
class student
{
public:
char name[10];
float score;
student(char[],float);//这里形式参数就是你要初试化的变量的类型。
~student();
};
student::student(char temp[10],float score1)
{
strcpy(name,temp);
score=score1;
cout<<name<<endl;
cout<<score<<endl;

}
student::~student()
{
cout<<"调用析构函数";
}
void main()
{
student stu("sunhong",99);
}

不知你是什么语言,这是java的

class abc
{
abc()//无参构造函数
{
//语句
}
abc(int i,Sting s)//有参构造函数
{
//语句
}
}

构造函数可以随意写,不必太拘泥于格式
,一般当你的类里面有变量(私有),就用到带参数的构造函数
,当然若不写带参数构造函数也可以,用个set*(int *等)方法传递也可
随意,就像独孤九剑,无着胜有招。就说到这,相比说多了你都会烦