c++ - 如何在默认构造函数 C++ 中初始化数组?
问题描述
所以我编辑的问题是:
我的 .h 文件是:
#ifndef FUNC
#define FUNC
using namespace std;
class func{
public:
double time[100];
double y_output[100];
func();
double expression(double t ,double y);
void rk4();
};
#endif
我的 .cpp 文件是
#include"func.h"
#include<iostream>
#include<cmath>
using namespace std;
func::func(): time{}, y_output{5} {} //tried this from one of the answers posted below.
double func::expression(double t, double y)
{
return (t+y)*sin(t*y);
}
void func::rk4()
{
float h = 0.2;
double k0,k1,k2,k3;
for(int i = 0;i < 100;i++)
{
k0 = (h*func::expression((time[i]),(y_output[i])));
k1 = (h*func::expression((time[i]+(h/2)),(y_output[i]+(k0/2))));
k2 = (h*func::expression((time[i]+(h/2)),(y_output[i]+(k1/2))));
k3 = (h*func::expression((time[i]+h),(y_output[i]+(k2/2))));
y_output[i+1] = y_output[i] + (k0+k1+k2+k3)/6;
time[i+1] = time[i] + h;
}
}
错误:
C:\Users\Reema\Desktop\ritikaS\RK4\func.cpp|6|error: mixing declarations and function-definitions is forbidden|
我不确定如何初始化数组的第一个元素。有人可以帮我吗?
另一种方法:
我只是尝试了另一种方法。我从 main 手动初始化了该值,而没有自己在类中创建构造函数,并且它起作用了。主文件
#include<iostream>
#include "func.h"
#include "func.cpp"
using namespace std;
int main()
{
func f;
double a = 5;
double b = 0;
f.y_output[0] = a;
f.time[0] = b;
return 0;
}
但是,我想知道数组是否可以在构造函数中初始化。任何人都可以帮我解决这个想法吗?
解决方案
我想初始化 y_output[0] = 5。
你这样做:
func::func(): time{}, y_output{5} {}
推荐阅读
- c# - EF Core Left Outer Join 失败,可空对象必须有一个值
- php - php mysql ssl 连接失败,访问被拒绝错误
- java - 如何从资源服务器中的 Spring Security OAuht2 Boot 中提取声明?
- xamarin.forms - Xamarin 方向信息.plist
- r - 从一个网页中抓取所有表格?
- python - *** 类型错误:get_value_by_attribute() 缺少 1 个必需的位置参数:“属性”
- android - 如何判断是否已正确添加外部依赖项(.aar)?
- swift - 如何从firebase标题文件夹Xcode中归档tableview
- google-cloud-platform - 在 Google Cloud 上并行运行多个 Colab 笔记本?
- java - 使用不同字体大小的 Java 打印发票