Effective C++面向对象与继承

发表于:2012-7-31 10:39

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:chentaihan    来源:51Testing软件测试网采编

  1:子类不要覆写父类的非虚函数。
  2:子类不要覆写从父类继承过来的默认参数
  3:子类与父类之间的赋值问题

  1:子类不要覆写父类的非虚函数。

  为了解释方便,先看一个简单的例子。

class A
{
 public:
  A(int d):data(d){  }

     void print()
  {
   cout<<"A print..."<<data<<endl;
  }

  virtual void test(int i=2)
  {
   cout<<"A test..."<<i<<endl;
  }
 private:
  int data;
};

class B:public A
{
 public :
  
  B(int d):A(d){  }
  void print()
  {
   cout<<"B print..."<<endl;
  }
  virtual void test(int i=4)
  {
   cout<<"B test..."<<i<<endl;
  }
};
 
//测试代码
int main() {
 {
     B b(5);
  b.print();
  A *a=&b;
  a->print(); 
  cout<<endl;
  b.test();
  a->test();
  cout<<endl;
  A a1=b;
  a1.test();
 }
 
  getchar();
     return 0;
}
 

  运行截图:

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号