Focus on ACE

订阅 ace-china
电子邮件:
浏览存于 groups.google.com 上的所有帖子

C++博客 首页 新随笔 联系 聚合 管理
  64 Posts :: 3 Stories :: 22 Comments :: 0 Trackbacks

父类的友元不会自动成为子类的友元;而且友元会破坏封装;C++的语方不允许(非成员)友元函数为虚函数。
但是,某些时候,必须通过友元才能实现一些操作符重载,如operator<<();如果为每个子类都实现operator<<()倒是一个可行的方法,但是显得很啰嗦。

如果能把友元定义为虚函数,则子类可以继承该友元的接口而无需重复声明友好那该多好啊?
本文则通过一种变通的方法巧妙达到虚函数的效果。

//基类 Base.



#pragma once
#include 
< iostream >
using   namespace  std;
class  Base
{
public :
  Base(
void );
  
~ Base( void );
public :
  
virtual   void  print(ostream &  output)  =   0 ;
  friend ostream
&   operator   << (ostream &  output,Base &  obj);
private :
  
char *  name_;
  
int  age_;
}
;

基类的实现 base.cpp
#include "StdAfx.h"
#include 
".\base.h"

Base::Base(
void)
{
  name_ 
= "This is data1";
  age_ 
= 18;
}


Base::
~Base(void)
{
}


void Base::print(ostream& output)
{
  output
<<"name = " <<name_<<endl;
  output
<<"age = "<<age_<<endl;
}


ostream
& operator<<(ostream& output,Base& obj)
{
  obj.print(output);
  
return output;
}


派生类的 Derived.h

#pragma once
#include 
"Base.h"
class Derived :public Base
{
public:
  Derived(
int score = 80);
  
~Derived(void);
  
virtual void print(ostream& output);
private:
  
int score_;
}
;

派生类的实现 Derived.cpp
#include "StdAfx.h"
#include 
".\derived.h"

Derived::Derived(
int score):score_(score)
{
  
}


Derived::
~Derived(void)
{
}


void Derived::print(ostream& output)
{
  Base::print(output);
  output
<<"score = "<<score_<<endl;
}


主程序main.cpp
// Test_VirtualFirendFunction.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream>
#include 
"Derived.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
  Derived  d;

  Derived  d2(
90);
  cout
<<d<<endl<<d2<<endl;
    
return 0;
}



屏幕输入结果
name = This is data1
age = 18
score = 80

name = This is data1
age = 18
score = 90

结果:
任何从Base派生类的,都可以利用cout<<obj的机制通过流进行输出。

同样道理,也可以利用此方法实现ACE_InputCDR  / ACE_OutputCDR对网络操作序列化操作。
(本文也是回答某网友关于派生类不能重载的问题的回复)

posted on 2006-04-17 22:12 Stone Jiang 阅读(1704) 评论(3)  编辑 收藏 引用 所属分类: ACEC++&OOPMiscellaneous

Feedback

# re: 巧用虚友元函数(原创) 2006-06-07 16:32 paopaoer
上面的例子我在vs 2005中编译不过;(  回复  更多评论
  

# re: 巧用虚友元函数(原创) 2006-06-13 09:22 paopaoer
原来是我自己搞错了;)
忘了继承  回复  更多评论
  

# re: 巧用虚友元函数(原创) 2007-10-16 09:37 aiirr
没有必要,用模板解决更合理  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理