473,398 Members | 2,389 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

C++ friend function

I've got a problem concerning the << operator. Although I've declared it as
a friend function it cannot access the private member of the class AVLtree.
Some code:

------------------
class AVLtree
{
public:
friend ostream& operator << (ostream& os, AVLtree& t){};
.... some unimportant stuff ...
private:
Tree tree;
};

ostream& operator << (ostream& os, AVLtree& t)
{
// if (t.tree!=NULL)
os << *(t.tree);
return os;
}
----------------

I cannot figure out why the compiler tells

error C2248: 'tree' : cannot access private member declared in class
'AVLtree'

Any advice?

Thanks in advance,
Matthias

--
Für emails Anweisung in der Adresse befolgen
Jul 22 '05 #1
10 4267
Der Andere wrote:
I've got a problem concerning the << operator. Although I've declared it as
a friend function it cannot access the private member of the class AVLtree.
Some code:
When posting code, please try to make it compilable. This is FAQ 5.8.

------------------
class AVLtree
{
public:
friend ostream& operator << (ostream& os, AVLtree& t){};
What's with the '{}'? I don't even know if that's legal, and it
certainly seems nonsensical. Are you defining the function here, or are
you defining it later?
... some unimportant stuff ...
private:
Tree tree;
};

ostream& operator << (ostream& os, AVLtree& t)
{
// if (t.tree!=NULL)
os << *(t.tree);
return os;
}


-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #2
Der Andere wrote:
I've got a problem concerning the << operator. Although I've declared it as
a friend function it cannot access the private member of the class AVLtree.
Some code:

------------------
class AVLtree
{
public:
friend ostream& operator << (ostream& os, AVLtree& t){};
Defined here.
... some unimportant stuff ...
private:
Tree tree;
};

ostream& operator << (ostream& os, AVLtree& t)
{
// if (t.tree!=NULL)
os << *(t.tree);
return os;
}
And here.
----------------

I cannot figure out why the compiler tells

error C2248: 'tree' : cannot access private member declared in class
'AVLtree'
Funny, mine says
"error: redefinition of `std::ostream& operator<<(std::ostream&, AVLtree&)".
Any advice?


Post the real code.

--
Regards,
Buster.
Jul 22 '05 #3
Ok then, underneath you'll find the complete code, as I got it. It should
compile now.

Regards,
Matthias

----------------------

#include <iostream>
#include <cassert>
#include <iomanip>

using namespace std;

typedef int T;

T max(T a, T b)
{
return a > b ? a : b ;
}

T min(T a, T b)
{
return a < b ? a : b ;
}

// ----------

enum Child {Left=0, Right=1};

Child opposite(Child k)
{
return Child(1-k);
}

// ----------

enum Balance { LeftBal=-1, Balanced=0, RightBal=1};

const bool deeper = true;
const bool sameDepth = false;

// ----------

typedef class Node* Tree;
const Tree Empty = NULL;

class Node
{
enum { Arity=2 };
Tree children[Arity];
int b;
T e;
public:
Node(T & v) : e(v), b(0) { for (int i=0;i<Arity;i+=1) children[i]=Empty; }
~Node();

friend int& bal(Tree p);
friend T& el (Tree p);
friend Tree & child(Tree p, Child k);
};

int& bal(Tree p) { assert(p); return p->b; }

T& el (Tree p) { assert(p); return p->e; }

Tree& child(Tree p, Child k) { assert(p); return p->children[k]; }

Tree& left(Tree p) { return child(p,Left); }

Tree& right(Tree p) { return child(p,Right); }

Node :: ~Node()
{
for (int i=0;i<Arity;i+=1)
if (children[i])
delete children[i];
}

// ----------

void rotate (Tree & root, Child c)
{
Child other = opposite(c);
assert(child(root,other)); // other Child should exist
Tree oldRoot = root;

root = child(root,other);
child(oldRoot,other) = child(root,c);
child(root,c) = oldRoot;

if (c==Left)
{
bal(oldRoot) -= 1+ max(bal(root),0);
bal(root) -= 1- min(bal(oldRoot),0);
}
else
{
bal(oldRoot) += 1- min(bal(root),0);
bal(root) += 1+ max(bal(oldRoot),0);
}
}

void rotateDubbel (Tree & root, Child c)
{
Child other = opposite(c);
rotate(child(root,other),other);
rotate(root,c);
}

// ----------

bool insertRight(Tree& tree, T v);
bool insertLeft(Tree& tree, T v);

bool insert(Tree& tree, T v) // returns true if tree becomes deeper
{
if (tree==Empty)
{
tree = new Node (v);
return deeper;
}
else if (v==el(tree))
return sameDepth;
else if (v<el(tree))
return insertLeft (tree,v);
else
return insertRight (tree,v);
}

bool insertRight(Tree& tree, T v)
{
if (insert(right(tree),v))
{
bal(tree) += 1;
switch(bal(tree))
{
case 2:
if (bal(right(tree)) == LeftBal)
rotateDubbel(tree,Left);
else
rotate(tree,Left);
return sameDepth;
case 1: return deeper;
case 0: return sameDepth;
default: assert(false);
}
}
else
return sameDepth;
}

bool insertLeft(Tree& tree, T v)
{
if (insert(left(tree),v))
{
bal(tree) -= 1;
switch(bal(tree))
{
case -2:
if (bal(left(tree)) == RightBal)
rotateDubbel(tree,Right);
else
rotate(tree,Right);
return sameDepth;
case -1: return deeper;
case 0: return sameDepth;
default: assert(false);
}
}
else
return sameDepth;
}

bool contains (Tree tree, T v)
{
if (tree == Empty)
return false;
else if (el(tree) == v)
return true;
else if (el(tree) < v)
return contains(right(tree),v);
else
return contains(left(tree),v);
}

bool sorted (Tree tree, T* v=NULL)
{
if (tree==Empty)
return true;
else
{
bool sl = sorted(left(tree),v);
if (v && el(tree) <= *v)
{
sl = false;
cout << "element " << *v << " staat op de verkeerde plaats\n";
}
v = &(el(tree));
return sorted(right(tree),v) && sl;
}
}

bool balanced (Tree tree, int& d)
{
if (tree==Empty)
{
d = 0;
return true;
}
else
{
int l=0, r=0;
bool bl = balanced(left(tree),l);
bool br = balanced(right(tree),r);
if (bal(tree) != r-l)
cout << "balansfactor in knoop met " << el(tree) << " verkeerd\n";
if (abs(r-l)>1)
cout << "avl tree is op knoop met " << el(tree) << " uit balans\n";
d = max(l,r) + 1;
return bl && br && bal(tree) == r-l && abs(r-l)<=1;
}
}
ostream& operator << (ostream& os, Node& n)
{
static int indent = 0;
const int stap = 3;
indent += stap;
if (right(&n)!=Empty)
os << *right(&n);
os << setw(indent-stap) << "" << el(&n) << " bal=" << bal(&n) << endl;
if (left(&n)!=Empty)
os << *left(&n);
indent -= stap;
return os;
}

// ----------
// ----------

class AVLtree
{
Tree tree;
public:
AVLtree(): tree(Empty) {}
~AVLtree() { if (tree) delete tree; }
friend ostream& operator << (ostream& os, AVLtree& t);
void Insert(T v) { insert(tree,v); }
bool Contains(T v) { return contains(tree,v); }
bool Sorted() { return sorted(tree); }
bool Balanced() {int d =0; return balanced(tree,d); }
};

ostream& operator << (ostream& os, AVLtree& t)
{
if (t.tree!=Empty)
os << *(t.tree);
return os;
}
// ----------

void main ()
{
// int val = 2;
// Node<int>* ptr = new Node<int>(val);
// cout << *ptr ;

/* Node<int>* t = Empty;
int rij[10] = {0,9,1,2,3,4,5,6,7,8};
for (int i = 0;i<10;i+=1)
{
insert(t,rij[i]);
cout << *t << endl;
}
*/

AVLtree t;
// int rij[10] = {0,9,1,2,4,4,5,6,7,8};
// int rij[10] = {5,3,7,2,4,6,1,1,1,1};
int rij[10] = {4,2,6,1,3,5,7,1,1,1};
for (int i = 0;i<10;i+=1)
{
t.Insert(rij[i]);
cout << t << endl;
if (!t.Sorted() || !t.Balanced())
cout << "Improper AVL tree\n";
}
for (int j = -1;j<11;j+=1)
cout << "contains " << j << " = " << boolalpha << t.Contains(j) << endl;
}
Jul 22 '05 #4
Der Andere wrote:
Ok then, underneath you'll find the complete code, as I got it. It should
compile now.


No, I get "error: `main' must return `int'".

Having fixed that, yes, it does compile. So, what, you fixed it?
What happened to "error C2248: 'tree' : cannot access private member
declared in class 'AVLtree'"?

--
Regards,
Buster.
Jul 22 '05 #5
> Der Andere wrote:
Ok then, underneath you'll find the complete code, as I got it. It should compile now.


No, I get "error: `main' must return `int'".

Having fixed that, yes, it does compile. So, what, you fixed it?
What happened to "error C2248: 'tree' : cannot access private member
declared in class 'AVLtree'"?


Errh, no, I didn't fix it. I've still got it.
I've never had this kind of problem with my compiler.
But if it works on your computer, the fault may be in my system, not in the
code?!

Regards,
Matthias
Jul 22 '05 #6
Der Andere wrote:
Errh, no, I didn't fix it. I've still got it.
I've never had this kind of problem with my compiler.
But if it works on your computer, the fault may be in my system, not in the
code?!


What compiler is it, and what version? I gather that with Visual C++,
anything before 7.1 was pretty crappy. If I see any problems with the
code you posted I'll let you know.

--
Regards,
Buster.
Jul 22 '05 #7
> > Errh, no, I didn't fix it. I've still got it.
I've never had this kind of problem with my compiler.
But if it works on your computer, the fault may be in my system, not in the code?!
What compiler is it, and what version? I gather that with Visual C++,
anything before 7.1 was pretty crappy.


Oh, I've got Visual C++ 6.0. So maybe Microsoft is the problem, not me ;-)
If I see any problems with the
code you posted I'll let you know.


Thanks!

Regards,
Matthias
Jul 22 '05 #8
On Tue, 13 Apr 2004 03:23:17 +0200, "Der Andere" <ma**************@gmx.net>
wrote:
> Errh, no, I didn't fix it. I've still got it.
> I've never had this kind of problem with my compiler.
> But if it works on your computer, the fault may be in my system, not inthe > code?!


What compiler is it, and what version? I gather that with Visual C++,
anything before 7.1 was pretty crappy.


Oh, I've got Visual C++ 6.0. So maybe Microsoft is the problem, not me ;-)


Anytime the words "friend function", "strange error" and "MSVC 6" are
uttered together, there's a good chance you're dealing with the infernal
"friend" bug in VC6. If you haven't yet, go download the latest service
pack (it is up to Service Pack 6 now) at:

http://msdn.microsoft.com/vstudio/do...6/default.aspx

-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #9
Der Andere wrote:
What compiler is it, and what version? I gather that with Visual C++,
anything before 7.1 was pretty crappy.


Oh, I've got Visual C++ 6.0. So maybe Microsoft is the problem, not me ;-)


Maybe so. I'm no expert.

Some things to try, without altering the correctness of your code:

(i) Add a forward declaration of the << overload before the definition
of the class of which it is a friend.

(ii) Define the friend function inside AVL tree class, so that it looks
a bit like an inline member function definition.
If I see any problems with the
code you posted I'll let you know.


Thanks!


--
Regards,
Buster.
Jul 22 '05 #10
Buster wrote:
Der Andere wrote:
Oh, I've got Visual C++ 6.0. So maybe Microsoft is the problem, not me
;-)


Maybe so. I'm no expert.


Looks like we're in the right place. Follow Leor's advice, not mine!

--
Regards,
Buster.
Jul 22 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. ...
2
by: Christophe Barbe | last post by:
I am not clear about friend functions of a template class. GCC (3.3.2) wants me to add <> after the friend function names in the class declaration and VisualC++ doesn't like that. template...
2
by: Christophe Barbe | last post by:
I posted a few days ago about the same problem but was not very clear. So here is my second take at it. Basically with GCC 3.3.2, I can't compile the example from the C++ FAQ Lite available...
5
by: Trevor Lango | last post by:
What is the appropriate syntax for placing a friend function that includes as one of it's parameters a pointer to the class object itself within the template class? I have the following: ...
10
by: Piotr Wyderski | last post by:
Hello, is it possible to reuse a friend operator which is defined inside a class? I'd like to obtain the following behaviour: class integer { integer operator +(signed long int v) const...
15
by: Samee Zahur | last post by:
Question: How do friend functions and static member functions differ in terms of functionality? I mean, neither necessarily needs an object of the class to be created before they are called and...
19
by: subramanian100in | last post by:
Stroustrup, in his book TC++PL 3rd Edition, in page 16, under the section '1.8 Advice' has mentioned the following: Don't use global data(use members) Don't use global functions Don't use...
6
by: WaterWalk | last post by:
I find friend declaration just very tricky. I tried the following examples on both MingW(gcc 3.4.2) and VC++ 2005. The results are surprising. Example1: namespace ns1 { class Test { friend...
9
by: wo3kie | last post by:
#include <iostream> #include <map> #include <utility> // // Base // / | \ // Derived1 Derived2 \ // \ | / // Derived3
21
by: H9XLrv5oXVNvHiUI | last post by:
Hi, I have a question about injecting friend functions within template classes. My question is specific to gcc (version 3.4.5) used in combination with mingw because this code (or at least code...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.