首页 > 编程语言 >[自用初学]c++的构造函数

[自用初学]c++的构造函数

时间:2022-12-12 19:44:31浏览次数:44  
标签:name int c++ 初学 默认 Student id 构造函数

#include <stdio.h>
#include <string.h>
 
class Student
{
private:
    int id;
    char name[32];
 
public:
    Student(int id, const char* name)
    {
        this->id = id;
        strcpy(this->name, name);
    }
};
 
int main()
{
    Student  s ( 201601, "shaofa");
    return 0;
}

例子如上:构造函数与类名相同,其中的形参都是类元素(id name),然后在函数体里给类元素进行了初始化。

一、构造函数的作用

构造函数的作用有三:1.让类可以以【Student s ( 201601, "shaofa");】的形式创建一个类对象;2.完成初始化;3.为对象的数据成员开辟内存空间。

如果不像上面一样写一个显式的构造函数,那么编译器会为类生成一个默认的构造函数, 称为 "默认构造函数", 默认构造函数不能完成对象数据成员的初始化, 只能给对象创建标识符, 并为对象中的数据成员开辟一定的内存空间。

二、默认构造函数

默认构造函数不传参,如果需要指定参数的初始化值,需要在函数体中指定。

#include <stdio.h>
#include <string.h>
 
class Student
{
private:
    int id;
    char name[32];
 
public:
    // 默认构造函数
    Student()
    {
        id = 0;
        name[0] = 0;
    }
 
    //  带参构造函数
    Student(int id, const char* name)
    {
        this->id = id;
        strcpy(this->name, name);
    }
};
 
int main()
{
    Student  s1 ;
    Student  s2 ( 201601, "shaofa");
    return 0;

而像上面那种带参数的显示构造函数,可以在传参的时候指定函数的初始化值,所以写一个显示构造函数更方便,就不需要去修改类里面的函数体了。

 

 

 

 

 

https://blog.csdn.net/qq_20386411/article/details/89417994

标签:name,int,c++,初学,默认,Student,id,构造函数
From: https://www.cnblogs.com/liuxiangyan/p/16976948.html

相关文章