其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
请能者解答:读C++大师Andrew Koenig>时产生的一点疑问

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

第八章“一个面向对象的范例” 范例是关于 +,-,*,/等数学表达式的处理。 程序如下:(C++Builder6.0 build 通过,运行不对。书内程序用明显少数字符错误,已改。) #include class Expr; class Expr_node { friend ostream& operator << ( ostream&, const Expr& ); friend class Expr; int use; protected: Expr_node(): use(1) {} virtual ~Expr_node() { } virtual void print( ostream& ) const = 0; }; //----------------------------------------------------- class Expr { friend ostream& operator << ( ostream&, const Expr& ); Expr_node * p; public: Expr( int ); Expr( const string&, Expr ); Expr( const string&, Expr, Expr ); ~Expr() { delete p; } public: Expr( const Expr& t ) { p = t.p; ++p->use; } Expr& operator = ( const Expr& t ); }; //---------------------------------------------------- class Int_node: public Expr_node { friend class Expr; int n; Int_node( int k ) : n( k ) {} void print( ostream& o ) const { o << n; } }; class Unary_node: public Expr_node { friend class Expr; string op; Expr opnd; Unary_node( const string a, Expr b ) : op(a), opnd(b) { } void print( ostream& o ) const { o << "(" << op << opnd << ")"; } }; class Binary_node: public Expr_node { friend class Expr; string op; Expr left; Expr right; Binary_node( const string& a, Expr b, Expr c ) : op(a), left(b), right(c) { } void print( ostream& o ) const { o << "(" << left << op << right << ")"; } }; ostream& operator << ( ostream& o, const Expr& t ) { t.p->print( o ); return o; }; Expr::Expr( int n ) { p = new Int_node( n ); }; Expr::Expr( const string& op, Expr t ) { p = new Unary_node( op, t ); }; Expr::Expr( const string& op, Expr left, Expr right ) { p = new Binary_node( op, left, right ); }; Expr& Expr::operator = ( const Expr& rhs ) { rhs.p -> use++; if ( --p->use == 0 ) delete p; p = rhs.p; return *this; }; //-------------------------------------------------- void main() { // Expr t = Expr( "*", Expr( "-", 5 ), Expr( "+", 3, 4 )); // Expr t0 = Expr( 123 ); cout << t0 << endl; Expr t00( 5 ); cout << t00 << endl; // 此例可以。 Expr t01( "-", t00 ); //不行 // t00 = Expr( "-", t00 ); // cout<<"sfsfsffs"<


相关文章

相关软件