C++ 友元

测试C++友元关键字

/************************************************************************/

/* FriendKey.h */

/************************************************************************/

#pragma once

#include <iostream>

class Planet

{

private:

int ID;

//注意此处的构造器是私有的,

//导致Earth类不能实例化其实例,

//Sphere可以,因为它是友元类。

Planet()

{

ID = 13;

}

friend class Sphere;

public:

void showID(void)

{

std::cout<<"id is "<<ID;

}

};

class Earth : public Planet

{

};

class Sphere : public Planet

{

};

/************************************************************************/

/* FriendKey.cpp : Defines the entry point for the console application. */

/************************************************************************/

//

#include "stdafx.h"

#include "FriendKey.h"

int _tmain (int argc, _TCHAR* argv[])

{

Sphere xxx; //此处工作得很好

xxx.showID();

getchar();

return 0;

}

/************************************************************************/

/* FriendKey.cpp : Defines the entry point for the console application. */

/************************************************************************/

//

#include "stdafx.h"

#include "FriendKey.h"

int _tmain (int argc, _TCHAR* argv[])

{

Earth xxx; //此处工作得很不好,运行会报错,编译能通过。

xxx.showID();

getchar();

return 0;

}

// if there is a class Nothing extended from Earth class, it can be initailized too.

// class Nothing : public Earth

// {

// }

// if class Earth is extended from Planet in this way:

// class Earth : virtual public Planet

// {

// }

// then the class Nothing would not be initialized.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值