473,586 Members | 2,754 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4301
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(ro ot,other)); // other Child should exist
Tree oldRoot = root;

root = child(root,othe r);
child(oldRoot,o ther) = 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(ro ot,other),other );
rotate(root,c);
}

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

bool insertRight(Tre e& 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(Tre e& tree, T v)
{
if (insert(right(t ree),v))
{
bal(tree) += 1;
switch(bal(tree ))
{
case 2:
if (bal(right(tree )) == LeftBal)
rotateDubbel(tr ee,Left);
else
rotate(tree,Lef t);
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(tr ee),v))
{
bal(tree) -= 1;
switch(bal(tree ))
{
case -2:
if (bal(left(tree) ) == RightBal)
rotateDubbel(tr ee,Right);
else
rotate(tree,Rig ht);
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(t ree),v);
}

bool sorted (Tree tree, T* v=NULL)
{
if (tree==Empty)
return true;
else
{
bool sl = sorted(left(tre e),v);
if (v && el(tree) <= *v)
{
sl = false;
cout << "element " << *v << " staat op de verkeerde plaats\n";
}
v = &(el(tree));
return sorted(right(tr ee),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(t ree),l);
bool br = balanced(right( tree),r);
if (bal(tree) != r-l)
cout << "balansfact or 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)!=Emp ty)
os << *right(&n);
os << setw(indent-stap) << "" << el(&n) << " bal=" << bal(&n) << endl;
if (left(&n)!=Empt y)
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

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

Similar topics

8
17853
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. Why can't the = (assignment) operator be overloaded as a friend function ? I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it said...
2
12512
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 <class T> class test{ test(void); ~test(void); friend bool operator== <> (const test<T> &p1, const test<T> &p2); }
2
10145
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 online at http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.15 Below are the two files that I compile with g++ foo.cpp -o...
5
2694
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: //**************************************************** // testClass.h //**************************************************** #ifndef TESTCLASS_H
10
2296
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
6575
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 either has access only to static members of the class (ie. assuming no object of the class is in scope - neither by arguments recieved nor by local...
19
2708
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 public data members. Don't use friends, except to avoid or . Consider the following scenarios: Scenario 1:
6
3157
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 void func()
9
2051
by: wo3kie | last post by:
#include <iostream> #include <map> #include <utility> // // Base // / | \ // Derived1 Derived2 \ // \ | / // Derived3
21
4680
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 that gets the same result) works as expected in visualc++. I know that this is probably not the right behavior for a compiler but it's the kind of...
0
7911
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8338
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7954
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6610
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3836
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1179
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.