[自用初学]c++的构造函数
2024-10-20 01:23:01
#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
最新文章
- iOS真机测试could not find developer disk image
- markdown命令语法
- ie浏览器 jsp中链接参数为中文的处理
- 线程池ThreadPoolExecutor、Executors参数详解与源代码分析
- JMeter源码集成到Eclipse
- Java 读Properties
- 【原创】MapReduce计数器
- 多台Mac电脑使用一个apple开发者账号
- 转:TestLink1.9.3测试用例:Excel转换XML工具<;二>;实现代码
- NoSql中的B-tree、B+tree和LSM-tree
- cf479E Riding in a Lift
- 用java字节码解释i++和++i(转)
- iOS TableView的分割线
- ArcGIS制图技巧系列(1)还原真实的植被
- Access text files using SQL statements by DB Query Analyzer
- C++基础知识--DAY2
- 10.25 正睿停课训练 Day9
- Spring Cloud Eureka 服务治理
- table 中 文字长度大于td宽度,导致文字换行 解决方案
- LeetCode143:Reorder List