简体   繁体   English

如何在默认构造函数 C++ 中初始化数组?

[英]How to initialize the array in default constructor C++?

So my edited question is:所以我编辑的问题是:

My .h file is:我的 .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

My .cpp file is我的 .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;

    }
}

Error:错误:

C:\Users\Reema\Desktop\ritikaS\RK4\func.cpp|6|error: mixing declarations and function-definitions is forbidden|

I am not sure how to initialize the array's first element.我不确定如何初始化数组的第一个元素。 Could anyone help me with it?有人可以帮我吗?

Another approach:另一种方法:

I just tried another method.我只是尝试了另一种方法。 I initialized the value manually from the main without creating a constructor in the class myself and it worked.我从 main 手动初始化了该值,而没有自己在类中创建构造函数,并且它起作用了。 main.cpp主程序

#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;
}

However, I was wondering if the array could be initialized inside the constructor.但是,我想知道是否可以在构造函数内部初始化数组。 Could anyone help me with the idea?有人可以帮我解决这个问题吗?

I want to initialize the y_output[0] = 5.我想初始化 y_output[0] = 5。

You do it like this:你这样做:

func::func(): time{}, y_output{5} {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM