C++如何将值从一个结构传递到另一个结构

C++ how to pass values from one structure to another?

本文关键字:结构 一个 另一个 C++      更新时间:2023-10-16

我有两种不同的结构。第一个是astm,它从.txt文件中读取数据,第二个是rebar,它使用结构一中的值来读取用户输入并进行计算。Stuct astm将充当菜单。我的问题是,如何将值从struct astm传递到struct reiba?

这是两种结构:

typedef struct
{
    int size; 
    double weight;
    double diameter;
 } astm;
 typedef struct
 {
    int size;// user input from astm.size
    double length; // user input
  } rebar;

这是.txt文件(实际文件不包含"sz"、"wt"或"diameter"):

sz   wt    diameter
2   0.167  0.250
3   0.376  0.375
4   0.668  0.500
5   1.043  0.625
6   1.502  0.750
7   2.044  0.875
8   2.670  1.000
9   3.400  1.128
10  4.303  1.27
11  5.313  1.41
14  7.65   1.693
18  13.6   2.257

示例:选择尺寸:4焓长:500

尺寸:4直径:0.500总重量=长度*重量=3340.0

回答您的问题:

astm myAstm;
myAstm.size = 5;
myAstm.weight = 30.0;
myAstm.diameter = 10;
rebar myRebar;
myRebar.size = myAstm.size;
myRebar.length = someCalculation(...)

然而,更好的方法是允许一个嵌入到另一个中:

typedef struct
{
    int size; 
    double weight;
    double diameter;
} astm;
typedef struct
{
    astm *myAstm;
    double length; // user input
} rebar;

这样做会减少多余的数据,并且可以只传递一个表示所有内容的结构。

astm myAstm;
myAstm.size = 5;
myAstm.weight = 30.0;
myAstm.diameter = 10;
rebar myRebar;
myRebar.myAstm = &myAstm;
myRebar.length = someCalculation(...)
// To get at the size attribute:
printf("size is %dn", myRebar.myAstm->size);

您可以重载赋值运算符。

但要小心,操作员过载并不总是最好的方法。

也许,转换函数或成员函数是更好的选择。

重载赋值运算符是一种可能的途径,但并不是很多人不喜欢这样。您也可以将它们直接传递给成员变量。

objRebar.size = objastm.size;

或者,您可以将这些创建为类,并添加一个成员函数来处理它。你有必要使用结构吗?

理想情况下,您希望有一个根据大小查找重量/直径的地图。由于您使用的是C++,请查看std::map(http://www.cplusplus.com/reference/stl/map/)。

astm更改为仅包含double weight, diameter;,当读取每个sz的txt文件时,执行map.insert(pair<int,astm>(sz,astm_var));

计算时,只需从map中查找astm,并从中计算总重量。

我会通过创建一个函数来解决这个问题:

void MoveInfo(const Astm &t, ReBar &bar);

但要做到这一点,您需要正确提供结构名称:

struct Astm { ... };
struct ReBar { ... };

请注意结构名称的位置。

如果rebar直接使用astm(而您实际上使用的是C++),您会得到这样的东西:

struct astm
{
    astm( int size, float weight, float diameter )
    : size( size )
    , weight( weight )
    , diameter( diameter )
    {}
    int size;
    double weight;
    double diameter;
};
struct rebar
{
    rebar( int size, double length )
    : size( size )
    , length( length )
    {}
    rebar( const astm& astm ) //<<< Uses astm directly
    : size( astm.size )
    {
        // Do something with rest of astm
    }
};

然而,情况似乎并非如此。听起来你想要这样的东西:

    std::vector<rebar> rebarVec;
    for ( int i = 0; i < numThings; ++i )
    {
        // Compute stuff from astm[ i ]
        rebar rebarItem( size, length );
        rebarVec.push_back( rebarItem );
    }

这就是你想要实现的吗?