读书人

解释一下C++程序解决方案

发布时间: 2012-03-24 14:00:46 作者: rapoo

解释一下C++程序
请高手帮我看看这个程序 小弟刚刚接触C++ 不是很懂 请把这个程序解释一下 这个程序很可能是错的.

#include <stdafx.h>
#include <iostream.h>
class Base
{public:
Base(int i) {b=i;}
void Print()=0;    
protected;
int b;
};
class Derive1:public Base
{public:
   Derive1(int i):Base(i){};   
void Print(){cout < < "Derive1 's Print() called. " < <endl;}
};
class Derive2:public Base
{
public:
Derive2(int i):Base(i){};
viod Print(){cout < < " Derive2 's Print() called. " < <endl}  
};
void fun( Base *obj  ){obj-> Print();}
void main()
{Derive1 *d1=new Derive1();
Derive2 *d2=new Derive2() ; 
fun(d1);
fun(d2);
}


[解决办法]
这是一个关于虚拟函数的用法实例,但是在基类里为什么printf不加虚拟virtual呢,这样的话这个程序就看不懂了。作为一个抽象基类,肯定是要声明为virtual的,否则当基类指针指向派生类时执行print就只能执行基类print了,毫无意义。

#include <stdafx.h>
#include <iostream.h>
class Base
{public:
Base(int i) {b=i;}
virtual void Print()=0;    //这里加上virtual
protected;
int b;
};
class Derive1:public Base
{public:
   Derive1(int i):Base(i){};   
void Print(){cout < < "Derive1 's Print() called. " < <endl;}
};
class Derive2:public Base
{
public:
Derive2(int i):Base(i){};
viod Print(){cout < < " Derive2 's Print() called. " < <endl}  
};
void fun( Base *obj  ){ obj-> Print();}
void main()
{ Derive1 *d1=new Derive1();
Derive2 *d2=new Derive2() ; 
fun(d1);
fun(d2);
}
[解决办法]
class Base
{
public:
Base(){}
Base(int i) : b(i) {};
virtual void Print() = 0; //要做纯虚函数,要添加virtual
protected:// : 不是 ;
int b;
};

class Derive1: public Base
{
public:
Derive1() {}
Derive1(int i) : Base(i){};
void Print(){cout < < "Derive1 's Print() called. " < <endl;}
};

class Derive2: public Base
{
public:
Derive2(){}
Derive2(int i) : Base(i) {};
void Print(){ cout < < " Derive2 's Print() called. " < <endl; }
// void 不是 viod , endl后面少了;
};

void fun(Base* obj){obj-> Print();}
void main()
{
//虚函数的多态性,要用基类指针.
Base* d1 = new Derive1(); //没有默认构造函数,会出错
Base* d2 = new Derive2();
fun(d1);
fun(d2);
}

读书人网 >C++

热点推荐