六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 37|回复: 0

C++ 友元

[复制链接]

升级  13.33%

72

主题

72

主题

72

主题

举人

Rank: 3Rank: 3

积分
240
 楼主| 发表于 2013-1-26 14:32:25 | 显示全部楼层 |阅读模式
测试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.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表