Riko Kurahashi
Riko Kurahashi

Reputation: 61

Printing a string with a class in C++?

#ifndef DATE_H
#define DATE_H

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

class Date{
private:
    unsigned int day;
    unsigned int month;
    string monthName;
    unsigned int year;
public:
    Date();
    void printNumeric() const;
    void printAlpha() const;
};
#endif

My header file

#include "Date.h"
#include <string>
using namespace std;


Date::Date(){
    month = 1;
    monthName = "January";
    day = 1;
    year = 1970;
}

void Date::printNumeric() const{
    cout << month << "/" << day << "/" << year;
}

void Date::printAlpha() const{
    cout << Date::monthName << " " << day << ", " << year;
}

and the actual code. My printNumeric function works fine according to the testbed but my printalpha is not producing the string month name. Am I supposed to do something with monthName so that it would produce the user input for the month name?

Upvotes: 0

Views: 143

Answers (2)

Abdellah IDRISSI
Abdellah IDRISSI

Reputation: 549

Using Date:: would be the same as using this or the member variable alone as long as you are within the class scope.

but you are better off using

cout << this->monthName << " " << day << ", " << year;

or

cout << monthName << " " << day << ", " << year;

Use Date:: when you have a static method to call or a public member to initialize outside the class scope for instance.

by the way, just in case you have another language background, string is part of iostream. So, do not use using namespace std; but std::cout you would then realize it when the compiler produces an error.

Upvotes: 0

Marurban
Marurban

Reputation: 1575

Remove Date:: and it should work

Upvotes: 3

Related Questions