测试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.