简体   繁体   English

C ++-将数据传递到结构

[英]C++ - passing data to struct

I'm translating a Fortran 77 code to C++ and the Fortran 77 uses common blocks. 我正在将Fortran 77代码转换为C ++,并且Fortran 77使用通用块。 I am trying to replace the common blocks with structs which I will then fill with values from a function and then call both to be used in my main. 我试图用结构替换公共块,然后用函数中的值填充它们,然后在我的main中调用这两个块。 At the moment my code looks like: 目前,我的代码如下所示:

#include <iostream> 
#include <cmath>
using namespace std;

// data_list 
struct data_list {
    double g, dw, Vel, M, dt, N;
    int Ioutp1, Ioutp2; 
    } values;

void data (data_list& val) {
    val.g = 9.80665;
    val.dw = 0.05; 
    val.Vel = 20.0;
    val.M = 128; 
    val.dt = 0.05; 
    val.N = 4000;
    val.Ioutp1 = 1;
    val.Ioutp2 = 1;
    }   

void Pierson_Moskowitz(data_list& val) {

/*
* Calculation of properties of Pierson_Moskowitz Spectrum
*/
    double Ug, Hs, A, B, Std;
    cout << values.Vel << "\t\t" << values.g; 
    Ug = values.Vel/values.g;
    cout << Ug << endl;

}   
int main() {
  data(values);
  //float dw = values.dw = 0.05;
  cout << values.dw << endl; 

}

This is just a test as at the moment my main isn't doing anything except printing a value. 这只是一个测试,因为目前我的主要工作除了打印值之外没有做任何事情。 What I want is for the variables that are given values in my data function to be able to be used throughout the code. 我想要的是在我的data函数中赋予值的变量能够在整个代码中使用。 At the moment, there are two things I'm confused about: 目前,我对两件事感到困惑:

1) My Pierson-Moskowitz function isn't printing anything for Ug. 1)我的Pierson-Moskowitz函数没有为Ug打印任何内容。 I don't understand why not? 我不明白为什么不呢? 2) I'm not sure that I even need the data function. 2)我不确定我是否需要data功能。 Essentially the Fortran code that I'm translating uses a subroutine to assign values to variables in a common block. 本质上,我要翻译的Fortran代码使用子例程为公用块中的变量分配值。 I am trying to do something similar by using a struct and then a function to fill it with values. 我试图通过使用一个结构,然后使用一个函数来填充值来做类似的事情。

This code is quite short and I plan to keep everything in one file. 这段代码很短,我打算将所有内容保存在一个文件中。 Any help is really appreciated!! 任何帮助都非常感谢!

You want to pass in a reference to your common block: 您要传递对公共块的引用:

void data (data_list& val) {

then you're changes will be to the common block rather than a copy. 那么你的改变将是公共块,而不是一个副本。

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

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