c++ Covariance issue with pointer return issue

2019-08-29 06:11发布

Since I had a lot of ambiguity in my post, I will redo it. This is a problem I am encountering in a project which I am upgrading from a visual studio 6.0 environment to a visual studio 2012 environment.

I have a class which is derived from the followinh mfc class (CPropertyPage) which contains the following function. file is afxdlgs.h (mfc class)

class CPropertyPage : public CDialog
{
public:
virtual CPropertySheet *GetParentSheet();
}

I also still seem to have the problem after changing the forward declaration. Which was a result due to my bad formulation. So I have changed it back to it's original form.

The derived class looks like this. header

class CBankDefImportSheet;
class CBankDefImportAssignPage : public CPropertyPage
{
protected:
    CBankDefImportSheet* GetParentSheet ();
}

in the cpp

#include "BankDefImportSheet.h"
CBankDefImportSheet* CBankDefImportAssignPage::GetParentSheet()
{
    return (CBankDefImportSheet *)GetParent ();
}

furthermore the CBangDefImportSheet is

class CBankDefImportSheet : public CPropertySheet
{}

when I compile I get the C2555 error that the return type differs and is not covariant from CPropertyPage::GetParentSheet.

I have tried adding the header of CBankDefImportSheet but that did not solve it. I have also read a possibility of being able to cast after the return type, but unsure if that would solve it, furthermore unsure of how to do it in this case.

EDIT: After solving, post below was part of the problem, however, so was const correctness. Shame on me!

in the header it should be specified as

 CBankDefImportSheet * GetParentSheet () const;

and furthermore in the cpp

 CBankDefImportSheet * CBankDefImportAssignPage::GetParentSheet() const
 {
     return ((CBankDefImportSheet *)GetParent ());
 }

2条回答
霸刀☆藐视天下
2楼-- · 2019-08-29 06:30

I answered my own question in the edit, but following advice i will also add it here. The main cause of my problem was that mfc dialog functions are const. Thus resulting in wrong covariance because of const correctness (or incorrectness in this case)

CBankDefImportSheet* GetParentSheet ();

in the header it should be specified as

CBankDefImportSheet * GetParentSheet () const;

and furthermore in the cpp

CBankDefImportSheet * CBankDefImportAssignPage::GetParentSheet() const
{
return ((CBankDefImportSheet *)GetParent ());
}

I'm glad this helped at least one other person already.

查看更多
\"骚年 ilove
3楼-- · 2019-08-29 06:44

The compiler needs to know at the point CDefImportSheetPage::GetParentSheet() is declared (where you've marked .h) that CDefImportSheet inherits from CPropertySheet.

It can't get that information from a simple forward declaration like:

class CDefImportSheet;

you'll need to include CDefImportSheet's header there instead.

查看更多
登录 后发表回答