2013-03-27 103 views
0

我在多態和純虛函數方面存在問題。我的主類純虛函數和繼承

#include<memory> 

class Shape 
{ 
    public: 
    Gdiplus::Point start; 
    Gdiplus::Point end; 

    std::shared_ptr<Gdiplus::Pen> m_pen; 

    virtual void Draw(Gdiplus::Graphics & m_GraphicsImage) = 0; 


    void setPen(std::shared_ptr<Gdiplus::Pen> pen2); 


    void setStart(int xPos, int yPos); 

    void setEnd(int xCor, int yCor); 

}; 

然後我有這個派生自Shape的類。 Line.h

#pragma once 


#include<memory> 

class Line: public Shape 
{ 
public: 
    void Draw(Gdiplus::Graphics & m_GraphicsImage); 
} 

這是我的line.cpp。

#include "stdafx.h" 
#include "Line.h" 
#include "ShapeMaker.h" 


void Line::Draw(Gdiplus::Graphics & m_GraphicsImage) 
{ 

    m_GraphicsImage.DrawLine(m_pen.get(),start.X,start.Y,end.X,end.Y); 
} 

在我主我宣佈Shape類型的共享指針多態性原因

std::shared_ptr<Shape> m_shape; 

,然後嘗試,並呼籲Line.cpp功能,但它不能正常工作,

LRESULT CDrawView::OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) 

{ 
int xPos= GET_X_LPARAM(lParam); 
int yPos = GET_Y_LPARAM(lParam); 
start.X = xPos; 
start.Y = yPos; 


//Line line; 
auto line = std::make_shared<Shape> (m_shape); 
std::shared_ptr<Gdiplus::Pen> myPen(pen.Clone()); 
line->setPen(myPen); 
line->setStart(xPos,yPos); 
return 0; 
} 

LRESULT CDrawView::OnLButtonUp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) 
{ 
int xPos= GET_X_LPARAM(lParam); 
int yPos = GET_Y_LPARAM(lParam); 
end.X = xPos; 
end.Y = yPos; 

//Pen pen(Color(0, 0, 255)); 
//Line line; 
auto line = std::make_shared<Shape> (m_shape); 
line->setEnd(xPos,yPos); 
line->Draw(m_GraphicsImage); 
m_shape.reset(); 


RedrawWindow(); 


return 0; 

} 現在我得到了drawview.cpp(54):error C2371:'line':redefinition;不同的基本類型 1> \畫\ drawview.cpp(53):看 '線' 的聲明

+3

我會用用'成員variable'命名命名功能*參數名*提醒你現在是'm_xxxxx'是去驅動任何習慣於處理以微軟爲中心的編碼習慣的人** **瘋狂**。現在殺死那隻鳥**。 – WhozCraig 2013-03-27 16:43:17

回答

0

void Draw(Gdiplus::Graphics & m_GraphicsImage) 

應該讀

void Line::Draw(Gdiplus::Graphics & m_GraphicsImage) 

沒有Line::你定義一個名爲Draw()的免費函數,恰好與Line::Draw()具有相同的簽名,但與其他方式無關。

+0

我仍然收到錯誤C2259:'Shape':當我嘗試編譯時無法實例化抽象類 – user1665569 2013-03-27 16:38:04

+0

正如Kiley提到的,您正在執行std :: make_shared以嘗試創建Shape實例。事情是Shape有一個純虛擬的Draw方法,你顯然想要這樣。這也意味着Shape永遠不會被實例化。你可以有Shape指針和Shape引用,但是它們應該總是指向派生的非抽象類。 – user2184879 2013-03-27 16:43:23

+0

嘿@ user2184879這就是我想要的。但我目前有兩個不同的功能,我只是想創建一個實例,並將其用於這兩個功能,但我得到一個行重新定義錯誤... – user1665569 2013-03-27 16:46:46

2

我相信這個問題是你的構造

std::make_shared<Shape> (m_shape); 

基本上是新的Shape(抽象類)。相反,你應該使用

std::make_shared<Line> (m_shape);