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

时间:2011-06-23 18:35:10

标签: c++ struct

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

这是两种结构:

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

6 个答案:

答案 0 :(得分:1)

回答你的问题:

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 %d\n", myRebar.myAstm->size);

答案 1 :(得分:0)

您可以重载赋值运算符。

但是要小心,运算符重载并不总是最好的方法。

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

答案 2 :(得分:0)

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

objRebar.size = objastm.size;

或者你可以将它们变成类并添加一个成员函数来为你处理它。你是否有必要使用结构?

答案 3 :(得分:0)

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

astm更改为仅保留double weight, diameter;,并在阅读每个sz的txt文件时,执行map.insert(pair<int,astm>(sz,astm_var));

计算时,只需从astm中查找map,然后从中评估总重量。

答案 4 :(得分:0)

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

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

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

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

注意结构名称的位置。

答案 5 :(得分:0)

如果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 );
    }

这是你想要完成的吗?

相关问题