问题
Can main function become friend function in C++ ?
#include "stdafx.h"
#include <iostream>
using namespace std;
class A {
public:
A():i(10){}
private:
int i;
friend int main();
};
int main()
{
A obj;
cout<<obj.i;
return 0;
}
回答1:
Can main function become friend function in C++ ?
Yes, it can.
The friend
declaration in your class A
grants function main()
the right of accessing the name of its non-public data members (in this case, i
):
friend int main();
The object obj
is default-constructed, and A
's constructor sets the value of i
to 10
:
A() : i(10) {}
// ^^^^^^^
// Initializes i to 10 during construction
Then, the value obj.i
is inserted into the standard output:
cout << obj.i;
// ^^^^^
// Would result in a compiler error without the friend declaration
回答2:
3.6.1 of the Standard (wording from draft n3936, but it's the same in C++03) says that:
The function
main
shall not be used within a program.
The exact meaning of this rule isn't clear. The Standard formally defines semantics for the related term odr-used, but not simply used.
To be safe, assume that this rule means that "The function main
shall not be named in a friend
declaration."
Interestingly, although the wording of this rule is identical to C++03, in that version what we now know as odr-used hadn't yet been renamed, and this rule was clearly referring to that concept. I wonder whether this was overlooked during the rename from used to odr-used. If the new term was intentionally not used here, the rationale for that decision might illuminate what uses, exactly, are intended to be forbidden.
Shafik found that the rename took place in N3214, and this rule was intentionally not changed to odr-use, although it doesn't explain why.
来源:https://stackoverflow.com/questions/17048904/c-friend-as-main-in-class