C ++:在类中作为主要的朋友 [英] C++: friend as main in class

查看:101
本文介绍了C ++:在类中作为主要的朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要功能可以在C ++中成为朋友函数吗?

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;
}


推荐答案


主要功能可以在C ++中成为朋友功能吗?

Can main function become friend function in C++ ?

是的,可以。

声明 A grant main()访问其非公开数据成员的名称的权利(在本例中为 i ):

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();

对象 obj A 的构造函数将 i 的值设置为 10

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

然后,值 obj.i 插入到标准输出中:

Then, the value obj.i is inserted into the standard output:

cout << obj.i;
//      ^^^^^
//      Would result in a compiler error without the friend declaration

这篇关于C ++:在类中作为主要的朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆