猿问

C++父类函数前加了virtual为什么还是没办法覆盖?

1   //main.cpp

#include"rect.h"

#include<iostream>

using namespace std;

rect::rect(double x,double y){

height = x;

longs = y;

cout<<"rect"<<endl; 

}

rect::~rect(){

cout<<"~rect"<<endl;

double rect::calc(){

cout<<"rect->calc()"<<endl;

return height*longs;

}

2    //shape.h

#ifndef SHAPE_H

#define SHAPE_H

class shape{

public:

shape();

~shape();

virtual double calc();

};


#endif

3//shape.cpp

#include"shape.h"

#include<iostream>

using namespace std;

shape::shape(){

cout<<"shape"<<endl;

}

shape::~shape(){

cout<<"~shape"<<endl;

}

double shape::calc(){

cout<<"shape->calc()"<<endl;

4//circle.h

#ifndef CIRCLE_H

#define CIRCLE_H

#include"shape.h"

class circle:public shape{

public:

circle(double r);

~circle();

double calc();

protected:

double m_dR; 

}; 

#endif

5//circle.cpp

#include"circle.h"

#include<iostream>

using namespace std;

double circle::calc(){

cout<<"circle->calc()"<<endl;

return 3.14*m_dR*m_dR;

}

circle::circle(double r){

m_dR = r;

cout<<"circle"<<endl;

}

circle::~circle(){

cout<<"~circle"<<endl;

}

6/rect.h

#ifndef RECT_H

#define RECT_H


#include"shape.h"

class rect:public shape{

public:

rect(double x,double y);

~rect();

double calc();

protected:

double height;

double longs;

}; 

#endif


7//rect.cpp

#include"rect.h"

#include<iostream>

using namespace std;

rect::rect(double x,double y){

height = x;

longs = y;

cout<<"rect"<<endl; 

}

rect::~rect(){

cout<<"~rect"<<endl;

double rect::calc(){

cout<<"rect->calc()"<<endl;

return height*longs;

}


半盏香茗
浏览 1785回答 1
1回答

皓韵儿

你代码粘的有问题吧,没有主函数。。。。还是???
随时随地看视频慕课网APP
我要回答