[英]How to initialize the array in default constructor 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} {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.