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

#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

 

 

 

 

 

#include"iostream"
#include"math.h"
#include"vector"
class single_point{

public :
    float x;
    float y;
    float z;
    single_point(float x_in,float y_in,float z_in)//构造函数
    {
        x = x_in;
        y = y_in;
        z = z_in;
    }
};
void calu(float x,float y,float& z1,float& z2){
    double k1=x*x+9/4.0*y*y-1;
    double k2=x*x+9/80.0*y*y;
    double a=1.0;
    double b=-pow(k2,1.0/3);
    double c=k1;
    z1=(-b+sqrt(b*b-4*a*c))/2*a ;
    z2=(-b-sqrt(b*b-4*a*c))/2*a ;
}
void collect(int split_level,float max_x ,float max_y,std::vector<single_point>& points){
    for (int i=0;i<=split_level;i++){
        float x=-max_x + split_level;
        for (int j=0;j<=split_level;j++){
            float y=-max_y + split_level;
            float z1;
            float z2;
            calu(x,y,z1,z2);
            single_point point1(x,y,z1);
            single_point point2(x,y,z2);
            points.push_back(point1);
            points.push_back(point2);
        }
    }
}
int main()
{
    std::vector<single_point> points;
    collect(100,1.5,1.0,points);
    return 0;
}

 

 

写法:

https://blog.csdn.net/m0_51271123/article/details/116503103

posted @ 2022-12-12 19:39  小千北同学超爱写代码  阅读(19)  评论(0编辑  收藏  举报