`
JonsenElizee
  • 浏览: 44746 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

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.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics