【问题标题】:C++ syntax/how to declare, fill and access an array within a classC++ 语法/如何在类中声明、填充和访问数组
【发布时间】:2011-07-21 18:09:49
【问题描述】:

如果我问的问题太大,请原谅我。我试图把它变成我在论坛中找到的一个例子。虽然这是一门课,但我只是想弄清楚我的功课,我的问题围绕着这个论坛问题——我不是要魔术代码来获得 A! (实际上是为了个人致富而参加这门课 p/fail 。) …… 我一直在使用以下问题的答案来尝试建立更好地理解我的 C++ 课程中的家庭作业问题。但我被卡住了,因为有一些基本的想法(只有一个?:-) 我想我就是不明白。我附加到这个问题底部的代码是我使用这个论坛示例,但我还没有意识到如何设置一个类内的数组。这是任务的一部分。

C++: syntax for accessing member struct from pointer to class

我在某种程度上解决了这个问题,因为我的背景是结构化程序员——我上这门课的原因是让我的大脑进入 oop 模式。所以有时我会在没有意识到的情况下走上一条偏离 oop 的轨道。

我的问题

我需要能够实例化“Foo”类的对象。该对象需要具有与之关联的 3 种事物的数组。呃..我认为在这种情况下,这些东西会被称为“酒吧”。这些东西具有属性“otherdata”和“andMoreData”。对象中只有一个名为“somedata”的数据(抱歉,我主要使用我在此处找到的代码中的变量名称)。

所以我是这样看的。

我有一个我实例化的对象,它被命名为“foo”,它属于“Foo”类。它有一个名为“somedata”的 ivar,我可以为其赋值。然后我想设置 3 次出现的“条形”数据。这些事件中的每一个都将由 ivars otherdata 和 and MoreData 组成。也许每个 ivar 的默认数据都是这样的 其他数据 = 1,更多数据 = 2

我不知道如何编写构造函数来将默认数据放入我的对象中。 我不知道如何访问对象中的数据以进行显示或更改。
... 我希望我没有在这里问太大的问题 ....

这是我一直试图从这个论坛重做的代码,希望我可以从这个解释中建立一个很好的理解,但是当我尝试创建一个构造函数时我被卡住了。 ....

/*  MY VARIATION ON FOOBAR
    Original EXamples found at 
https://stackoverflow.com/questions/915106/c-syntax-for-accessing-member-struct-from-pointer-to-class

*/

#include <iostream>
#include <iomanip>
using namespace std;

const int MAX_num = 3;
class Foo{
    // I think I have this right, that Bar is the name of the struct
    //   and 'mybar' is an ivar within the class, with a data type of 'Bar'
    //   
public:
    struct Bar{
        int otherdata;
        int andMoreData;
    } 
    mybar; // I think I am saying that mybar is an ivar of type Bar

    /* Here I tried to move forward with what I wanted to do, but the
     compiler thought it was a bad idea
    */ 
    // Here I'm attempting to create a constructor with default data
     { // set default data for mybar
        otherdata = 1;
        andMoreData = 2;
    }
    // Here I'm attempting to fill an array 'nmybar' with 3 occurances of my struct
    //  but I don't know how to say that it's associated with that struct/variable
    //  actually this seems like the WRONG place to do this, but my teachers example
    //    does something similar in the .h file (and of course his example works fine, but I 
    //  don't understand it

    nmybar[MAX_num];    // this calls mybar() MAX_num times

    int somedata;
};

int main(){

    // I instantiate class Foo and name my object 'foo'

    Foo foo;

    // Then I want to refer to the mybar portion of my foo object
    //   mybar could contain more than one variable itself, in this case
    //      it doesn't. so I am just referring to the one variable that
    //         a 'Bar' variable can contain, which is 'otherdata'
    //  HERE I added a second variable to the struct to make sure I understood how 
    //   to use it , ok that works

    foo.mybar.otherdata = 5;
    foo.mybar.andMoreData = 6;
    cout << foo.mybar.otherdata << endl ;
    cout << foo.mybar.andMoreData << endl ;

    return 0;
}

/*
 Program loaded.
 run
 [Switching to process 1297]
 Running…
 5
 6

 Debugger stopped.
 Program exited with status value:0. */

【问题讨论】:

  • 如果您编辑问题以修正格式,您可能会更快地获得回复。只需选择整个代码部分并点击编辑器上方的 {} 图标。

标签: c++ arrays class constructor struct


【解决方案1】:

我稍微清理了代码并生成了一个工作示例。

#include <iostream>
#include <iomanip>

using namespace std;

const int MAX_num = 3;

class Foo
{
public:
   struct Bar {
      int otherdata;
      int andMoreData;

      Bar () : otherdata(1), andMoreData(2) { };
   };

   Bar mybar[MAX_num]; // Array of MAX_num Bar's
   int somedata;
};

int main ()
{
   Foo foo;

   foo.mybar[0].otherdata   = 5; // [0] for first element, [1] for second, [2] for third
   foo.mybar[0].andMoreData = 6; // don't try to access higher positions, as the array has
                                 // only three elements

   cout << foo.mybar[0].otherdata << endl;   // 5
   cout << foo.mybar[0].andMoreData << endl; // 6

   cout << foo.mybar[1].otherdata << endl;   // 1
   cout << foo.mybar[1].andMoreData << endl; // 2

   return 0;
}

但看起来你有点不知道该怎么做。我建议您阅读 c++ 教程或书籍(在 stackoverflow 上有一些关于好的初学者书籍的条目)从头开始学习 c++。虽然一开始可能看起来更耗时,但这样你会学到更多。

【讨论】:

  • 感谢你们俩。我要坐下来通过这些。我知道它看起来像我不知道我在做什么!我正在考虑删除帖子并重新开始。我实际上有一本我一直在努力使用的教科书(我什至会做题并检查我的答案)。这个特殊的问题让我很难过,因为它没有像书中的其他问题那样布置,于是我去问老师,他说,结构就像数据类型。
【解决方案2】:

您为 Bar 编写一个构造函数,就像编写任何构造函数一样。如果 Bar 不在 Foo 中,那么它将是这样的:

struct Bar {
    Bar();
    int otherdata;
    int andMoreData;
};

Bar::Bar(): otherdata(1), andMoreData(2) { }

当你把 Bar 放在 Foo 里面时,它变成:

class Foo {
    struct Bar {
        Bar();
        int otherdata;
        int andMoreData;
    };
};

Foo::Bar::Bar(): otherdata(1), andMoreData(2) { }

然后为 Foo 的每个实例提供 3 个 Bar 对象实例,您可以执行以下操作:

class Foo {
    struct Bar {
        Bar();
        int otherdata;
        int andMoreData;
    };
    Bar bars[3];
};

Foo::Bar::Bar(): otherdata(1), andMoreData(2) { }

还有其他方法可以格式化,但以上是最惯用的。你会注意到bars 变量和Bar 类在上面都是私有的。人们普遍认为成员变量在一个类中应该是私有的(我告诉你这是因为你说你的目的是更好地理解 OO。)有时可以接受使结构(Bar)本身公开可用,但如果结构只是为了方便类,那么最好也将其设为私有。

【讨论】:

  • 感谢您以“最地道”的方式讲述。是的,这就是我想要的。试图做到这一点并得到它。
【解决方案3】:
const int MAX_num = 3;
class Foo{
public:
    struct Bar{
        Bar() { // Constructor - initializes a Bar instance
            otherdata = 1;
            andMoreData = 2;
        }
        int otherdata;
        int andMoreData;
    };
    Bar mybar; // Separating the Bar type from the mybar variable. Your original syntax is valid, but this is more common
    Bar nmybar[MAX_num]; // nmybar is an array of MAX_num Bar's
    int somedata;
};

【讨论】:

  • 我正在尝试为答案投票,但我一直被告知要登录或注册。我已登录,当我尝试这样做时,它会告诉我。
【解决方案4】:

好的,非常感谢发帖的人,我能够编写出我理解的代码示例。

然后我能够将我学到的想法应用到我的课堂问题中。

我现在可以使用我需要的结构和数组来创建类!现在我可以重新设计我的家庭作业解决方案的其余部分(我得到了运行机器工作的所有点点滴滴,但只喝了一杯)以适应所需的课程。谢谢!

这是我的新示例类,包含真实姓名等。

/* C++ syntax/how to declare, fill and access an array within a class 从 MacGucky 的解决方案开始 */

包括

包括

使用命名空间标准;

const int UNIQUE_DRINKS = 5;

/* 类 DrinkMachine { 私人的: 串饮; 双倍成本; 诠释饮料左; 双倍收钱;

*/

类 DrinkMachine { 民众: /* 所以“DrinkMachine”类中有两个成员 一个是'moneyCollected' 另一个是“瓶子” “瓶子”有 3 个属性: a) 'drink' - 饮料的名称 b)“成本”——一杯饮料多少钱 c) 'drinksLeft' - 机器中每种独特饮料的库存量 */ 结构瓶{ 串饮; 双倍成本; int DrinksLeft;

    // this is a constructor for 'Bottles' It puts default data into an instance OF 'Bar'
    Bottles () : drink("cola"), cost(0.75), drinksLeft(20) { };
};
Bottles myBottles[UNIQUE_DRINKS]; // myBottles is an Array of UNIQUE_DRINKS Bottles
// refer to 'myBottles' like a member, that has children   (two dots for it's children)
//              versus one dot for moneyCollected

double moneyCollected;

};

int main() { // 实例化 DrinkMachine,创建一个名为 'Building1' 的对象

cout << "Lets's fill up the drink machine in Building 1 ! " << endl ;
DrinkMachine Building1;
Building1.moneyCollected = 20.00;

// objectname.ARRAYNAME[position].ivarWithinStruct

// KEEP ALL the defaults for first Bottles item (Cola)
// most of the rest matches the defaults except name and price on water

    Building1.myBottles[1].drink   = "grape soda"; 
    Building1.myBottles[2].drink   = "root bear"; 
    Building1.myBottles[3].drink   = "orange soda"; 
    Building1.myBottles[4].drink   = "bottled water"; 
    Building1.myBottles[4].cost    = 1.00; 

for (int i=1; i<=4;i++) {
    cout << Building1.myBottles[i].drink  ;    
    cout << " " ;
    cout << Building1.myBottles[i].cost  ;   
        cout << " " ;
    cout << Building1.myBottles[i].drinksLeft ;   //  
    cout << endl;
}
cout << "\t * * * " << endl ;
cout << "\t Total Bucks Collected Today " << Building1.moneyCollected << endl ;
return 0;

}

/* 正在将程序加载到调试器中…… 程序已加载。 跑步 【切换到进程3332】 跑步… 给1号楼的饮料机加满水吧! 葡萄汽水 0.75 20 根熊 0.75 20 橙汽水 0.75 20 瓶装水 1 20


今天收集的总钱数 20

调试器停止。 程序以状态值退出:0。 */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多