Quick C++ Help Please

正在查看此主题的用户

Stonewall382

Knight at Arms
Hi, I just need the syntactically correct code for an initialization function inside a data structure please.  I can't find it online, and my book is lost in my room.  We haven't gotten to this yet in class, but it would really help for a program I'm making.  My current code (won't compile) looks like this:

插入代码块:
struct FighterNames
{
   string HomieNames [NUM_HOMIE_NAMES];
   string CopNames    [NUM_COP_NAMES];

   void InitNames
   {
      HomieNames = ["Tim", "Don", "Steve"];
   }
};

Thank you to anyone who helps--it's much appreciated.

I'll delete this when I get an answer or figure it out myself. :wink:

D'oh!  I think I just got it:
插入代码块:
struct FighterNames
{
   string HomieNames [NUM_HOMIE_NAMES];
   string CopNames   [NUM_COP_NAMES];

   void InitNames ()
   {
      HomieNames [0] = "Tim";
      HomieNames [1] = "Don";
      HomieNames [2] = "Steve";
   }
};
 
Yeah. Except since it's a struct, the default access is private.

You need a public: tag before the ctor.
 
:neutral:

Don't know what you just said.  Maybe that explains why it doesn't seem to be assigning names to fighters right now.  Would you mind reiterating that please?

插入代码块:
struct FighterNames
{
   string HomieNames [NUM_HOMIE_NAMES];
   string CopNames   [NUM_COP_NAMES];

   public: void InitNames ()
   {
      HomieNames [0] = "Tim";
      HomieNames [1] = "Don";
      HomieNames [2] = "Steve";

      CopNames   [0] = "O'Donnel";
      CopNames   [1] = "O'Dooley";
      CopNames   [2] = "McBride" ;
   }
};
Compiles, but doesn't help--my fighters still aren't receiving names.

Edit:  Is that what you meant?
 
Ooh, I thought it was a constructor, sorry. Yeah, the public makes it so that
it is now accessible, which means that you can call it from other code. But since
it's not a ctor, it needs to be static, as well. You'd be better off just initializing
the array directly, as in:

string HomieNames [NUM_HOMIE_NAMES] = {"Tim", "Bart", ...


The ctor has to have the SAME name as the class/struct. It doesn't return anything either,
so no void return signature. Given that you're using C++, if you want a real object, you should
label it a class - though there's not much difference between classes and structs, it's preferable.
 
The compiler I'm using won't allow the direct initialization, as it's made by one of the professor's here at school (I tried that :sad:).  So how do I call it?

Thanks for the help guys.:smile:
 
Probably something I've forgotten again.

change  public: void InitNames ()
to

public:  FighterNames()

making it a ctor.
 
后退
顶部 底部