【发布时间】: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