C++如何将值从一个结构传递到另一个结构
C++ how to pass values from one structure to another?
我有两种不同的结构。第一个是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 );
}
这就是你想要实现的吗?
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 静态结构和一个定义规则
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- 在学习数据结构之前对STL有一个了解是好的吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 使用完数据结构后清空数据结构是一个好习惯吗?
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- error dllimport 函数的定义不允许在一个特定的联合中,而其他类、结构和联合将按预期导出
- std::transform 将一个结构数组复制到另一个结构数组
- C++:如何做一个链表,结构作为参数传递?
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 两个附带的类层次结构-一个好的设计模式