This is such a simple issue, it's embarrassing to have to ask.. but I've been having trouble with this theoretical issue of defining string arrays (and even integers!) outside of their class. Here's some code:

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

class desu {
public:
  string ok[4]; // Give string 4 elements of space
} s;

s.ok[] = {"one", "two", "three", "four"}; 
// Calling upon object "s" to access class "desu"

int main()
{
    cout << "Write some generic stuff here";
  return 0;
}

Now, do I actually need to define a public function WITHIN class 'desu' (privatizing the variables, of course) and, outside the class, call upon that function just to fill my string array?

Granted, I've even tried this with integers (just to make sure that I'm not screwing up with string arrays) and i still get compile errors, eg:

#include <iostream>

using namespace std;

class desu {
public:
  int lol;
} s;

s.lol=5;

int main()
{
    cout << "Write some generic stuff here";
  return 0;
}

Thank you dearly for any help.

The application begins at the main function, so you can't assign a value to a variable outside of a function unless it's initialization. Here, you have two options.

#include <iostream>
using namespace std;

class desu {
public:
  int lol;
} s;

int main()
{
  [B]s.lol = 5;[/B]
  cout << "Write some generic stuff here";
  return 0;
}

Or...

#include <iostream>
using namespace std;

class desu {
public:
  int lol;

  [B]desu(int val) {
    lol = val;
  }[/B]
} [B]s( 5 )[/B];

int main()
{
  cout << "Write some generic stuff here";
  return 0;
}

Hope this helps.

Thank you for the help. Your examples do work for integers perfectly. I tried initializing that string array, in main().. however, it brought up more errors. Here's what i'm basically working with:

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

class desu {

public:
  string ok[4];

} s;

int main()
{
    s.ok[]={"one", "two", "three", "four"};

    cout << "Blah blah";

 return 0;
}

Appreciate the help!

You can only initialize an array like that, otherwise you have to assign the string to each array element seperatly like this:

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

class desu {

public:
  string ok[4];

} s;

int main()
{
  s.ok[0] = "one";
  s.ok[1] = "two";
  s.ok[2] = "three";
  s.ok[3] = "four";

  cout << "Blah blah";
  return 0;
}

To do it by initialization, you do this:

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

int main()
{
  string ok[4] = {"one", "two", "three", "four"};
  return 0;
}

Hope this helps.

Ah, okay, thanks. I was under the impression that the bracket usage in defining string arrays was simply a shorthand for manual initializing them one by one (ie, interchangable).

This article has been dead for over six months. Start a new discussion instead.