为什么这里没有覆盖? (C ++)

时间:2015-11-14 16:41:37

标签: c++ inheritance

我写了两个类--Polygon和Rectangle。 在他们两个中,我写了一个构造函数,询问用户多边形的点。我期望在读取方法中覆盖 - 但它没有发生。 这是代码:

Polygon.h:

#ifndef __POLYGON_H
#define __POLYGON_H

#include "Point.h"
#include <vector>
#include <string>
class Polygon {
public:
    Polygon();
    Polygon(int c);

protected:
    virtual std::vector<Point*> read();

private:
    const int color;
    std::string type;
    std::vector<Point*> _points;
};

Polygon.cpp:

#include "Point.h"
#include "Polygon.h"
#include <iostream>

using std::cout;
using std::endl;
using std::vector;
using std::cin;

Polygon::Polygon():
color(-1)
{}

Polygon::Polygon(int c):
color(c),
type("polygon"),
_points(this->read()) //******the problem is here*******
{
}

std::vector<Point*> Polygon:: read(){
    int x,y=0;
    vector<Point*> temp;
    cout<<"enter new x value and y value for point. enter '!' for finishing"<<endl;
    while (std::cin>>x && cin>>y){
        Point* p=new Point(x,y);
        temp.push_back(p);
        cout<<"enter new x value and y value for point. enter '!' for finishing"<<endl;
    }
    return temp;
}

Rectangle.h:

#ifndef RECTANGLE_H
#define RECTANGLE_H

#include "Point.h"
#include "Polygon.h"

class Rectangle: public Polygon
{
    public:
        Rectangle(int c);
        virtual std::string getType();
    protected:
        virtual std::vector<Point*> read();
    private:
        Rectangle();
};

#endif 

Rectangle.cpp:

#include "Rectangle.h"
#include "Point.h"
#include "Polygon.h"
#include<vector>
#include<iostream>

using namespace std;

Rectangle::Rectangle(int c):
    Polygon(c)
{
}
std::vector<Point*> Rectangle:: read()
{
    int x,y=0;
    std::vector<Point*> temp;
    cout<<"enter 4 rectangle valid points"<<endl;
    for (int i=1; i<5; i++){
        cout<<"enter new x value and y value for point "<< i << ". enter '!' for finishing"<<endl;
        std::cin>>x;
        std::cin>>y;
        Point* p=new Point(x,y);
        temp.push_back(p);
    }
    return temp;
}

现在,当我在main编写此代码时:

Polygon* r1=new Rectangle(1);

我得到了一行:enter new x value and y value for point. enter '!' for finishing - 来自Polygon的读取方法,按照我的预期设置了Rectangle。

为什么read方法没有覆盖?我还尝试在Rectangle的read方法中写override,它保持不变。

0 个答案:

没有答案