繁体   English   中英

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

[英]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.

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