Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

C++: friend as main in class

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...