![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Oct 2004
Posts: 73
Rep Power: 4
![]() |
Hi all!
![]() I was working with classes, and was trying to test the friend directive. In the code below I keep getting the following error on compilation: c:\c__~1\new\prac\struct~1\friend.cpp:35: no `int stack::compare(stack, stack)' member function declared in class `stack' The code is below. I hope someone can help me out? ![]() Cheers ![]() #include <iostream.h>
const int SIZE = 100;
class stack {
private:
int count;
int data[SIZE];
public:
void init( void );
void push( const int item );
int pop( void );
friend int compare( const stack &stack1, const stack &stack2 );
};
void stack::init( void )
{
count = 0;
};
void stack::push( const int item )
{
data[count] = item;
++count;
};
int stack::pop( void )
{
--count;
return(data[count]);
};
int stack::compare( const stack stack1, const stack stack2 )
{
if( stack1.count != stack2.count )
return(0);
for( int i = 0; i < stack1.count; ++i )
{
if( stack1.data[i] != stack2.data[i] )
return(0);
};
return(1);
};
main()
{
class stack myStack1;
class stack myStack2;
myStack1.push(4);
myStack2.push(3);
cout << compare( myStack1, myStack2 ) << '\n';
return(0);
}; |
|
|
|
|
|
#2 |
|
Professional Programmer
Join Date: Nov 2004
Posts: 250
Rep Power: 4
![]() |
You have two problems:
>int stack::compare compare is a friend, not a member. You don't qualify friends as if they were members unless they actually are. ![]() >friend int compare( const stack &stack1, const stack &stack2 ); >int compare( const stack stack1, const stack stack2 ) Notice how the declaration takes references to a const stack and the definition takes const stack objects. These are two different functions and the compiler will treat them as overloads. Change the definition to match the declaration and the code will compile: class stack {
private:
int count;
int data[SIZE];
public:
void init( void );
void push( const int item );
int pop( void );
friend int compare( const stack &stack1, const stack &stack2 );
};
...
int compare( const stack &stack1, const stack &stack2 )
{
if( stack1.count != stack2.count )
return(0);
for( int i = 0; i < stack1.count; ++i )
{
if( stack1.data[i] != stack2.data[i] )
return(0);
};
return(1);
}; |
|
|
|
|
|
#3 |
|
Programmer
Join Date: Oct 2004
Posts: 73
Rep Power: 4
![]() |
Hey!
Oh, Oh, Oh what a stupid mistake to make!!! Thanks for pointing out where I went wrong. At least, know I know where I went wrong ![]() Cheers ![]() |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|