C ++继承,基础方法隐藏 [英] C++ inheritance, base methods hidden

查看:94
本文介绍了C ++继承,基础方法隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的C ++基类,派生类示例。

I have a simple C++ base class, derived class example.

// Base.hpp 
#pragma once

class Base
{
public:
    virtual float getData();
    virtual void setData(float a, float b);
    virtual void setData(float d);

protected:
    float data;
};

//Base.cpp
#include "stdafx.h"
#include "Base.hpp"

float Base::getData()
{ 
    return data; 
}

void Base::setData(float a, float b)
{ 
    setData(a);
}

void Base::setData(float d)
{ 
    data = d;
}

//Derived.hpp
#pragma once
#include "Base.hpp"

class Derived
    : public Base
{
public:
    virtual void setData(float d);
};

//Derived.cpp
#include "stdafx.h"
#include "Derived.hpp"

void Derived::setData(float d)
{
    data = d + 10.0f;
}

如果我现在创建一个指向Base的指针, >

If I now make a pointer to the Base this compiles fine.

//Main.cpp
#include "stdafx.h"
#include "Base.hpp"
#include "Derived.hpp"

Base *obj = new Derived();

但是如果我指向Derived类的指针,那么编译器(VC 2008和2010) :

But if I make a pointer to the Derived class, then the compiler (VC 2008 and 2010) complains that:

Main.cpp(12): error C2660: 'Derived::setData' : function does not take 2 arguments

此处是导致此错误的代码:

And here is the code that causes this error:

//Main.cpp
#include "stdafx.h"
#include "Base.hpp"
#include "Derived.hpp"

Derived *obj = new Derived();

似乎基类方法被隐藏。我的印象是,由于基类方法是虚拟的,即使从Derived指针查看,或者我错了,它们应该是可见的。

It seems that the base class methods are being hidden. I was under the impression that since the base class methods are virtual they should be visible even when viewed from the Derived pointer, or am I wrong?

推荐答案

这是C ++名称查找的工件。基本算法是编译器将以当前值的类型开始,并向上继续层次结构,直到找到具有目标名称的类型的成员为止。然后它将仅对具有给定名称的类型的成员执行重载解析。它不会在父类型上考虑同名的成员。

This is an artifact of C++ name lookup. The basic algorithm is the compiler will start at the type of the current value and proceed up the hierarchy until it finds a member on the type which has the target name. It will then do overload resolution on only the members of that type with the given name. It does not consider members of the same name on parent types.

解决此问题的方法是重新定义 Derived 上的函数,并将它们转发到 Base

The way to work around this is to redefine the functions on Derived and just forward them up to Base

class Derived {
  ...
  void setData(float a, float b);
}

void Derived::setData(float a, float b) {
  Base::setData(a,b);
}

此外,您可以使用使用声明

class Derived {
  using Base::setData;
  ...
}

关于使用

  • http://publib.boulder.ibm.com/infocenter/comphelp/v101v121/index.jsp?topic=/com.ibm.xlcpp101.aix.doc/language_ref/using_declaration_class_members.html

这篇关于C ++继承,基础方法隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆