I want to use this array as part of my class. I have tried several different angles trying to get it to work but with out success. I have been checking to see if it works by simply using "cout << dayName[3];" It is printing nothing at all. can someone show me the proper way to initialize this array of strings?
First I tried this:
//dayType.h, the specification file for the class dayType
#include <iostream>
#include <string>
usingnamespace std;
class dayType{
private:
string day; // To hold single instance of the name of a weekday.
const string dayName[7]; // holds the names of the of the seven weekdays
//"Sunday", "Monday", "Tuesday", "Wedensday", "Thursday", "Friday", "Saturday"
int dayNumber; // To hold an int representation of the location of a spicific day
//within the array
void setDay(); // Function to set the DayType variable "day" to the name of a
//weekday. This function recieves a call from promptUser() and begins by asking
//the user to enter the day to set.
//Postcondition: after the user enters the information in the form of a
//weekday name this function sets the day to that value.
public:
void promptUser(); // Asks the user if they want to set the day and if yes
//prompts the user to set the day by entering the day name via function setDay.
//Postcondition: If the user chooses to enter Y for yes when prompted this
//function calls setDay()
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13
//dayTypeImp
#include <iostream>
#include <string>
#include "dayType.h"
usingnamespace std;
//======================= dayType functions ====================================
dayType::dayType()
{
const string dayName[] = {"Sunday", "Monday", "Tuesday", "Wedensday", "Thursday", "Friday", "Saturday"};
int dayNumber = 0;
string day; // To hold the string name of the day.
}
Yea. It dosn't have to be a const. I tried initializing it with the values(day name strings) in the constructor only and the only other place dayName was mentioned was in the header. It was not a const when I tried that. This is what I had in the header: string dayName[7];
and this is what I had in the constructor:
1 2 3 4 5 6
dayType::dayType()
{
string dayName[] = {"Sunday", "Monday", "Tuesday", "Wedensday", "Thursday", "Friday", "Saturday"};
int dayNumber = 0;
string day; // To hold the string name of the day.
}
The problem is that in your constructor you are declaring a new, local variable called dayName, and initializing the contents of that. You are not initializing the contents of the data member called dayName, because your local variable is hiding it.