#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

最新文章

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

热门文章

  1. SQL注入之延时注入(10)
  2. php 反序列化字符串逃逸
  3. elasticsearch组件
  4. JS字符串拼接的方法及性能比较
  5. 思科IPsecVPN建立
  6. BIP change数据改变前的事件
  7. DOS批处理自动定期清除生成的备份文件
  8. nacos 1.4.2 建立集群,公司启动linux服务器常用命令
  9. HttpClient常用的一些常识
  10. mybatis-关联查询3-自关联查询