简体   繁体   中英

How to initialize the array in default constructor C++?

So my edited question is:

My .h file is:

#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

#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.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.

You do it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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