Cannot getMonth function inside overloaded << function.Referen

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 589 Views - Last Post: 17 April 2013 - 10:36 PM Rate Topic: -----

#1 AndrewSa  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 93
  • Joined: 02-November 12

Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 03:14 PM

I currently overloaded the << stream operator to output the class Date in the format that I originally wanted using x , y , x.

However x (being the date month) I would like outputted as the months name (January), not just the value (1).

So I created this public getMonth() function in class Date to take the value operand2.month in the ostream overloaded function to return the months name.

By doing this I get an error at the Date::getMonth(operand2.month) part.

It says, non static member reference must be relative to a specific object.

I have no clue what that means. I have been tinkering with the code for several hours trying to get the getMonth() function to work properly. I am going about this completely the wrong way?

Thanks.

ostream &operator<<( ostream &output, const Date &operand2)  //display object in form (x,y,z)
{ 
	

	output <<  Date::getMonth(operand2.month) << " " << operand2.day << ", " << operand2.year; // othewise, outputs numbers in complex number form
	return output;
}// end function

string Date::getMonth( const Date &operand2) const
{
	string m[13]={ "January" , "February", "March" , "April", "May", "June", "July", "August", "September", "October", "November" , "December"};
	string monthname;

	monthname = m[operand2.month];

	return monthname;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Cannot getMonth function inside overloaded << function.Referen

#2 jimblumberg  Icon User is online

  • member icon


Reputation: 4103
  • View blog
  • Posts: 12,707
  • Joined: 25-December 09

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 03:34 PM

If this function is part of your class you don't need to pass a Date into it if all you want is to return the string date.

string Date::getMonth()
{
	string monthname[13]={ "January" , "February", "March" , "April", "May", "June", "July", "August", "September", "October", "November" , "December"};

	return monthname[month];
}


Jim
Was This Post Helpful? 1
  • +
  • -

#3 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3590
  • View blog
  • Posts: 11,168
  • Joined: 05-May 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 03:34 PM

It means that you need an instance of Date to be able to call a method.on the class. E.g. operand2.getMonth(operand2.month)

If you declare a method with an explicit "static" modifer, then you don't need an instance.

Sent from my T-Mobile G2 using Tapatalk 2
Was This Post Helpful? 1
  • +
  • -

#4 AndrewSa  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 93
  • Joined: 02-November 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 03:54 PM

I changed it like so. However the << before operand2.getMonth() has an error that states, no operator << matches these operands. I've also tried calling the function getMonth() without the operand2. It seems no matter how I manipulate the code, I get an error. Is there a more simpler way of doing this?








ostream &operator<<( ostream &output, const Date &operand2)  //display object in form (x,y,z)
{ 
	
	
	output <<noshowpos << operand2.getMonth() << " " << operand2.day << ", " << operand2.year; // othewise, outputs numbers in complex number form
	return output;
}// end function

string Date::getMonth() 
{
	string m[13]={ "January" , "February", "March" , "April", "May", "June", "July", "August", "September", "October", "November" , "December"};

	return m[month];
}









View Postjimblumberg, on 15 April 2013 - 03:34 PM, said:

If this function is part of your class you don't need to pass a Date into it if all you want is to return the string date.

string Date::getMonth()
{
	string monthname[13]={ "January" , "February", "March" , "April", "May", "June", "July", "August", "September", "October", "November" , "December"};

	return monthname[month];
}


Jim

Was This Post Helpful? 0
  • +
  • -

#5 jimblumberg  Icon User is online

  • member icon


Reputation: 4103
  • View blog
  • Posts: 12,707
  • Joined: 25-December 09

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 03:58 PM

Please show the smallest possible complete program that illustrates your problem. Really need to see how your class is defined.

Jim
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3590
  • View blog
  • Posts: 11,168
  • Joined: 05-May 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 05:10 PM

Is your code significantly different from your other thread?
Was This Post Helpful? 0
  • +
  • -

#7 AndrewSa  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 93
  • Joined: 02-November 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 06:50 PM

Ok, here is all my code for this program. I still can't figure this one out. Very frustrating to say the least.
Sorry if I posted too much code but I figured it may help resolve the problem. I will have to erase the unnecessary code later so classmates can't duplicate my work.

I feel that it has something to do with the way I am either calling my function or defining it. I have a hard time understanding scope when it comes to multiple classes/objects/functions.

The initial error I get states that I cannot convert the this pointer due to declaring the overloaded << operator's second parameter as a Const. When I remove the const, which I don't think I should have to do to resolve the problem, I get about 60 errors in relation to the C++ ostream function/header. I have been tinkering with this code for about 5 hours with no prevail.

#include <iostream>
#include <iomanip>
#include "Date.h" // include Date class definition
using namespace std;

// constructor confirms proper value for month; calls
Date::Date( int mn, int dy, int yr)
	: month( checkMonth(mn)), 
	  day( checkDay(dy) ),						// validation of date in comparison to month
	  year( yr )
{
}
// end Date constructor

Date test;

// utility function to confirm proper day value based on 
// month and year; handles leap years, too
int Date::checkDay( int testDay ) const
{
   static const int daysPerMonth[ monthsPerYear + 1 ] = 
      { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

   // determine whether testDay is valid for specified month
   if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
      return testDay;

   // February 29 check for leap year 
   if ( month == 2 && testDay == 29 && ( year % 400 == 0 || 
      ( year % 4 == 0 && year % 100 != 0 ) ) )
      return testDay;

   cout << "Invalid day (" << testDay << ") set to 1.\n";
   return 2; // leave object in consistent state if bad value ;; return 2 for day
} // end function checkDay


//function checkMonth
int Date::checkMonth( int testMonth ) const
{
   
   // determine whether testMonth is valid for specified month
   if ( testMonth > 0 && testMonth<13)
      return testMonth;

   
   return 1; // leave object in consistent state if bad value ;; return 1 for month
} // end function checkMonth

//overload eqality operator
bool Date::operator==( const Date &operand2 ) const
{
	if (month != operand2.month || day != operand2.day || year != operand2.year)
		return false;

	return true;
} // end function


ostream &operator<<( ostream &output, const Date &operand2)  //display object in form (x,y,z)
{ 
	
	
	output <<noshowpos << operand2.getMonth() << " " << operand2.day << ", " << operand2.year; // othewise, outputs numbers in complex number form
	return output;
}// end function

string Date::getMonth() 
{
	string m[13]={ "January" , "February", "March" , "April", "May", "June", "July", "August", "September", "October", "November" , "December"};

	return m[month];
}




#include <iostream>
#include <iomanip>
using std::cout;

#include "Complex.h" // Complex class definition

// Constructor
Complex::Complex( double realPart, double imaginaryPart ) 
   : real( realPart ),
   imaginary( imaginaryPart ) 
{ 
} // end Complex constructor


// ostream operator
ostream &operator<<( ostream &output, const Complex &operand2)  //display object in for (x,y)
{ 
	
	output << noshowpos<< operand2.real << " " <<showpos << operand2.imaginary << "i "; // othewise, outputs numbers in complex number form
	return output;
}// end function



//overload eqality operator
bool Complex::operator==( const Complex &operand2 ) const
{
	if (real != operand2.real || imaginary != operand2.imaginary)
		return false;

	return true;
} // end function






#ifndef COMPLEX_H
#define COMPLEX_H


using namespace std;
#include <iostream>


class Complex
{
   friend ostream &operator<<( ostream &, const Complex & ); //const because object will not change
public:
   Complex( double = 0.0, double = 0.0 ); // constructor
   bool operator==( const Complex & ) const;   // equality operator
   
   
private:
   double real; // real part
   double imaginary; // imaginary part
}; // end class Complex

#endif






#ifndef DATE_H
#define DATE_H
using namespace std;



class Date 
{
	friend ostream &operator<<( ostream &, const Date & ); //const because object will not change

public:
	
   static const int monthsPerYear = 12; // number of months in a year

   Date(int m = 1 ,int d =2  , int y = 1990); // default constructor
   bool operator==( const Date & ) const;   // equality operator
   string getMonth();
   
private:
   int month; // 1-12 (January-December)
   int day; // 1-31 based on month
   int year; // any year
   


   // utility function to check if day is proper for month and year
   int checkDay( int ) const; 
   int checkMonth( int ) const; 
}; // end class Date

#endif





#include "Complex.h"
#include "Date.h"

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


// isEqualTo<T> deleted per poster's request. 

	// outputMessage that takes type bool as an arguement and outputs message appropriately
	void outputMessage( bool t)
	{
		if( t == true )
			cout << " are equal" << endl;
		else
			cout << " are \"NOT\" equal" << endl;
		
		
	}


int main()
{
	 
	

	Complex w(10,5);				// create Complex Objects for comparison
	Complex x(10,54);
	Complex y(10,-5);
	Complex z(-10,-5);

	Date d(2,31,2011);				// create Date Objects for comparison
	Date e(2,13,2011);
	Date f(2,14,2011);
	Date g(1,13,2011);

	char a={'a'};					// create and initialize characters
	char b={'b'};
	char c={'c'};

	string h="abcdefg";				// create and initialize strings
	string i="abcdefh";
	string j="-abcdefg";


		//int tests
		cout << "*** Integers Tests *** \n"
		<< "Integers: " << 1 << " and " << 1 ;
		outputMessage(isEqualTo(1,1));
			
		cout << "Integers: " << 2 << " and " << 4 ;
		outputMessage(isEqualTo(2,4));

		cout << "Integers: " << -1 << " and " << 1 ;
		outputMessage(isEqualTo(-1,1));

		cout << "Integers: " << -1 << " and " << -1 ;
		outputMessage(isEqualTo(1,1));


		//char tests
		cout << "\n\n\n*** Character Tests *** \n"
		<< "Character: " << a << " and " << a ;
		outputMessage(isEqualTo(a,a));
			
		cout << "Character: " << a << " and " << c ;
		outputMessage(isEqualTo(a,c));

		cout << "Character: " << b << " and " << c ;
		outputMessage(isEqualTo(b,c));

		cout << "Characters: " << b << " and " << b ;
		outputMessage(isEqualTo(b,B)/>/>);



		//double tests
		cout << "\n\n\n*** Double Tests *** \n"
		<< "Double Numbers: " << 2.2 << " and " << 2.2 ;
		outputMessage(isEqualTo(2.2,2.2));
			
		cout << "Double Numbers: " << 2.2 << " and " << 2.3 ;
		outputMessage(isEqualTo(2.2,2.3));

		cout << "Double Numbers: " << -2.2 << " and " << 2.2 ;
		outputMessage(isEqualTo(-2.2,2.2));

		cout << "Double Numbers: " << -2.2 << " and " << -2.2 ;
		outputMessage(isEqualTo(-2.2,-2.2));



	
		//complex tests
		cout << "\n\n\n*** Complex Tests *** \n"
		<< "Class Objects: " << w << " and " << w ;
		outputMessage(isEqualTo(w,w));
			
		cout << "Class Objects: " << w << " and " << x ;
		outputMessage(isEqualTo(w,x));

		cout << "Class Objects: " << y << " and " << w ;
		outputMessage(isEqualTo(g,e));

		cout << "Class Objects: " << z << " and " << z ;
		outputMessage(isEqualTo(z,z));



		//string tests
		cout << "\n\n\n*** String Tests *** \n"
		<< "String: " << h << " and " << h ;
		outputMessage(isEqualTo(h,h));
			
		cout << "String: " << h << " and " << i ;
		outputMessage(isEqualTo(h,i));

		cout << "String: " << j << " and " << i ;
		outputMessage(isEqualTo(j,i));

		cout << "String: " << j << " and " << j ;
		outputMessage(isEqualTo(j,j));



		//date tests
		cout << "\n\n\n*** Date Tests *** \n"
		<< "Date Objects: " << d << " and " << d ;
		outputMessage(isEqualTo(d,d));
			
		cout << "Date Objects: " << e << " and " << f ;
		outputMessage(isEqualTo(e,f));

		cout << "Date Objects: " << g << " and " << e ;
		outputMessage(isEqualTo(y,w));

		cout << "Date Objects: " << g << " and " << g ;
		outputMessage(isEqualTo(z,z));

		cout << endl;
	
	system("PAUSE");
}




View Postjimblumberg, on 15 April 2013 - 03:58 PM, said:

Please show the smallest possible complete program that illustrates your problem. Really need to see how your class is defined.

Jim



View PostSkydiver, on 15 April 2013 - 05:10 PM, said:

Is your code significantly different from your other thread?

This post has been edited by Skydiver: 15 April 2013 - 08:14 PM
Reason for edit:: Deleted isEqualTo<T> per poster's request.

Was This Post Helpful? 0
  • +
  • -

#8 jimblumberg  Icon User is online

  • member icon


Reputation: 4103
  • View blog
  • Posts: 12,707
  • Joined: 25-December 09

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 06:58 PM

Since you are using the const qualifier in your overloaded operator<< your getMonth() function must also have the const qualifier.

In future please post the complete error messages, these messages have important information embedded within them to aid in locating and fixing the errors.




Jim
Was This Post Helpful? 1
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3590
  • View blog
  • Posts: 11,168
  • Joined: 05-May 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 07:16 PM

jimblumberg makes a point to emphasize how important it is to post the complete error message. When I tried compiling your code both with the MSVC compiler and the GNU compiler, both point to one common error:

Error from MSVC:
error C2662: 'Date::getMonth' : cannot convert 'this' pointer from 'const Date' to 'Date &'


Error from GNU:
error: passing 'const Date' as 'this' argument of 'std::string Date::getMonth()' discards qualifiers [-fpermissive]



Once you fix that, there you'll finally get the error that you were reporting only from MSVC. (The GNU compiler seems to happily compile the rest.) The error:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)



Anyway, this is due to not including the <string> header file. If you include that prior to declaring your Date class, things should work much better.
Was This Post Helpful? 1
  • +
  • -

#10 AndrewSa  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 93
  • Joined: 02-November 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 07:26 PM

Here is 4 different ways I have written my code. I am completely lost.

When I have the getMonth() receive a const qualifier, much like the << function , I receive this error.
<< operand2.getMonth(operand2.month) <<

1>  Date.cpp
1>c:\users\andrew1\desktop\cisp400\cisp400assignment6\a6cisp400\date.cpp(69): error C2662: 'Date::getMonth' : cannot convert 'this' pointer from 'const Date' to 'Date &'
1>          Conversion loses qualifiers



When I remove the const qualifier from both functions, I get this error instead.
<< operand2.getMonth() <<


1>c:\users\andrew1\desktop\cisp400\cisp400assignment6\a6cisp400\date.cpp(69): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(726): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)'
1>          with
1>          [


And when I write my code like this (without const qualifiers as well)...


 << getMonth() <<


1>------ Build started: Project: A6CISP400, Configuration: Debug Win32 ------
1>  Date.cpp
1>c:\users\andrew1\desktop\cisp400\cisp400assignment6\a6cisp400\date.cpp(69): error C3861: 'getMonth': identifier not found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========



And like this ...

<< Date::getMonth() <<


I get ...


1>c:\users\andrew1\desktop\cisp400\cisp400assignment6\a6cisp400\date.cpp(69): error C2352: 'Date::getMonth' : illegal call of non-static member function
1>          c:\users\andrew1\desktop\cisp400\cisp400assignment6\a6cisp400\date.h(23) : see declaration of 'Date::getMonth'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========




I


View Postjimblumberg, on 15 April 2013 - 06:58 PM, said:

Since you are using the const qualifier in your overloaded operator<< your getMonth() function must also have the const qualifier.

In future please post the complete error messages, these messages have important information embedded within them to aid in locating and fixing the errors.




Jim

Was This Post Helpful? 0
  • +
  • -

#11 AndrewSa  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 93
  • Joined: 02-November 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 07:33 PM

Sorry, did not see your answer as well. Wow... missing a <string> header. It works now. Thanks for both your help. YES!

P.S.- How do I edit posts? I can edit my last post but not my previous ones. I'd like to remove the post with ALL my code so other students in my class can't copy.

Thanks.

View PostSkydiver, on 15 April 2013 - 07:16 PM, said:

Anyway, this is due to not including the <string> header file. If you include that prior to declaring your Date class, things should work much better.

Was This Post Helpful? 0
  • +
  • -

#12 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3590
  • View blog
  • Posts: 11,168
  • Joined: 05-May 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 07:37 PM

Please don't edit old posts. It loses continuity for anybody catching up on a thread.

Yes, the downside is that others may plagiarize your work, but there's been more than one occurrence where people have actually plagiarized broken code, and then post a question here claiming the code as their own and asking why it doesn't work! :wacko:
Was This Post Helpful? 0
  • +
  • -

#13 AndrewSa  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 93
  • Joined: 02-November 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 07:41 PM

Sorry, one more question. So my code works good now but I dont think I full grasp the idea of why it did not work properly before hand, outside of the missing header. So if I am understanding this correctly, my overloaded function's second argument (an object) was declared const, meaning it should not change. But my getMonth() function that receives no parameters, and obviously does not contain const arguments some how.... changes the the << 2nd argument? And the compiler prevents this from occurring? Interesting. I have a lot to learn.

Thanks again.

You guys are awesome.
Was This Post Helpful? 0
  • +
  • -

#14 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3590
  • View blog
  • Posts: 11,168
  • Joined: 05-May 12

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 08:11 PM

Here's a small program that illustrates the problem with the MS compiler. (The GNU compiler seems to be happy even with -Wall.)
#include <iostream>

// Uncomment the following line to fix C2679 error
// #include <string>

using namespace std;

class Foo
{
public:

    friend ostream & operator<<(ostream & out, Foo & foo);

private:
    string GetValue();
};

string Foo::GetValue()
{
    return "Bar";
}

ostream & operator<<(ostream & out, Foo & foo)
{
    out << foo.GetValue();
    return out;
}

int main()
{
    Foo foo;
    cout << foo << endl;
    return 0;
}


Was This Post Helpful? 1
  • +
  • -

#15 jimblumberg  Icon User is online

  • member icon


Reputation: 4103
  • View blog
  • Posts: 12,707
  • Joined: 25-December 09

Re: Cannot getMonth function inside overloaded << function.Referen

Posted 15 April 2013 - 08:53 PM

This is one of the reasons you should never rely on some other file including a required header. Always include the header files when you use an item that requires that header.

The string header seems to be included by one of the other header files, but this behavior should not be relied upon. The standard doesn't specify what include files each include file includes so one compiler may include a header that another compiler doesn't.

Another reason to post the complete error messages is that once you learn to read these errors you will find that they do start to make sense.

Jim

This post has been edited by jimblumberg: 15 April 2013 - 08:56 PM

Was This Post Helpful? 2
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2