简体   繁体   English

c ++使用结构作为私有成员变量

[英]c++ using struct for private member variables

here is what I need to do for my homework这是我需要做的家庭作业


data members representing the: name, address, city, state and ZIP code for both the sender and the recipient of the package, in addition to data members that store the weight (in ounces) and cost per ounce to ship the package.数据成员表示:包裹发件人和收件人的姓名、地址、城市、州和邮政编码,以及存储重量(以盎司为单位)和每盎司运输包裹的成本的数据成员。


these are the memb vars for my class, and it says I need the name,address, city, state, and zip for both sender and recipient, so I think i should make a struct with those 5 variables, and just made 2 instances of the struct one for sender and one for recipient instead of making 2 names, adresses and etc...这些是我班级的成员变量,它说我需要发件人和收件人的姓名、地址、城市、州和邮编,所以我想我应该用这 5 个变量创建一个结构,并且只创建了 2 个实例一个用于发件人的结构,一个用于收件人的结构,而不是制作 2 个姓名、地址等...

But idk if thats possible or right to do, and how to do it?但是,如果那是可能的或正确的,以及如何做? Any help?有什么帮助吗?

Thanks)谢谢)

Here is what I have:这是我所拥有的:

class Package {
private:
    string name;
    string adress;
    string city;
    string state;
    int zip;
    double weight;
    double costPerOunce;
public:
    <#member functions#>
};

Also here is what I need for this class, and also another question.这也是我这门课需要的东西,还有另一个问题。 How would I initialize the struct members for class, and do the set fuctions if my member vars are struct?如果我的成员变量是结构,我将如何初始化类的结构成员,并执行集合函数? How would the syntax look like?语法会是什么样子? Thank you!谢谢!

在此处输入图片说明

You should declare your struct outside of your Package Class.你应该在你的包类之外声明你的结构。 As for initializing the variables within the struct, I believe Dave S offered a good solution in having a separate set function.至于初始化结构体中的变量,我相信 Dave S 提供了一个很好的解决方案,即拥有一个单独的 set 函数。 This way you can call your set function within your constructor for the sender and recipient which will avoid code duplication.通过这种方式,您可以在构造函数中为发送者和接收者调用 set 函数,这将避免代码重复。

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

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