Re: Three simple questions
"Lorry Astra" wrote:
1. First question
using namespace std;
struct X;
struct Y {
private:
void f(X*);
};
struct X {
private:
int i;
public:
void initialize();
friend void Y::f(X*);
};
Compilor told me that error occurred on ???friend void
Y::f(X*);???. But I think
if you really want to declare a private function( f(X*) )
in ???struct Y??? and
you want that this function has a friend relationship with
???struct X???. how
can I coding it?
You can't do it. Private functions are private and not
accessible from outside the class. You can make the whole
struct `Y' as a friend, though:
struct X;
struct Y {
private:
void f(X*);
};
struct X {
private:
int i;
public:
void initialize();
//friend void Y::f(X*);
friend struct Y;
};
// access private member of X
void Y::f(X* p) { p->i = 3; }
2. Second question
Code which is written in second question has not any
relationship with the
first question.
Code sample:
using namespace std;
struct Y {
public:
friend void h();
};
I know that in C++ every function should been declared
before using it. But
in ???struct Y???, I think, h() function is not declared
properly, I believe the
correct way is like this below:
using namespace std;
void h();
struct Y {
public:
friend void h();
};
But both of the two code samples are all right. Could you
tell me why?
Because the Standard allows it. Moreover, you can define
function's body inside a class, too:
struct Y {
public:
friend void h() { ... }
};
Nevertheless, function `h' is declared at file scope. This
is one of the "features" of C++. See here for more info:
"Defining Friend Functions in Class Declarations"
http://msdn2.microsoft.com/en-us/library/928ecaad(vs.80).aspx
3. Third question
Code sample1:
using namespace std;
struct X;
struct Y {
private:
void f(X*);
};
Code sample2:
using namespace std;
struct X;
struct Y {
private:
void f(X);
};
I think ???1??? is right but ???2??? is wrong, because in ???2???, I
just can find a
declaration of ???struct X??? instead of a definition about
???struct X???. I think
during the runtime, if function ???f??? takes an object
parameter( f(X) ) instead
of a pointer ( f(X*) ), C++ should know the size of
???struct X??? definitely. So
I think this code sample should be right:
Code sample:
using namespace std;
struct X
{
Int I;
};
struct Y {
private:
void f(X);
};
You're correct about this one.
Alex