2011-06-23 85 views
1

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

这里有两种结构:

这里是.txt文件(实际的文件不包含 “SZ”, “重量” 或 “直径”):

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 Enther长度:500

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

+0

听起来像指针工作。我想如果你内部的结构成员定义为指针,然后只是分享它们之间的实际值,那就行了。虽然可能会给你一些漂亮的绳索,让自己依靠。 –

+1

你的struct声明是c样式的,所以这真的是C++吗? – crashmstr

+1

目前尚不清楚你想要达到的目标。 “将struct astm的值传递给struct rebar”是什么意思? –

回答

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); 
0

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

objRebar.size = objastm.size; 

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

+0

是的,我必须使用一个结构。 –

+0

@Stephen罗杰斯:它是否也有成员函数? –

0

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

变化astm阅读每个sz txt文件只double weight, diameter;当持有,做一个map.insert(pair<int,astm>(sz,astm_var));

计算时,只需查找从mapastm和评价它的总重量。

0

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

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

但要做到这一点,你需要有适当提供的结构名称:

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

通知的结构名的位置。

0

如果螺纹钢采用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); 
    } 

这是你想要完成?

相关问题