为什么我不能使用子类的指针访问基类的公共函数? [英] Why can I not access a public function of a base class with a pointer of a subClass?

查看:26
本文介绍了为什么我不能使用子类的指针访问基类的公共函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么会收到错误C2660:'SubClass :: Data':函数没有2个参数".当我尝试编译我的项目时.

I am not sure why I am getting an "error C2660: 'SubClass::Data' : function does not take 2 arguments". when i try to compile my project.

我有一个带有名为data的函数的基类.该函数带有一个参数,Data的重载带有2个参数.在我的子类中,我重写了带有1个参数的数据函数.现在,当我尝试从指向子类的指针调用数据重载时,会收到上述编译错误.

I have a base class with a function called data. The function takes one argument, There is an overload of Data that takes 2 arguments. In my subClass I override the data function taking 1 argument. Now when I try to call the overload of data from a pointer to subClass I receive the above compile error.

class Base : public CDocument
{
Public:
virtual CString&    Data( UINT index);      
CString     Data( UINT index, int pos); 
};
class SubClass : public Base
{
Public:
virtual CString&    Data( UINT index);      

};

Void SomeOtherFunction()
{
subType* test = new subType();
test->Data( 1, 1);// will not compile
((Base*)test)->Data(1,1); // compiles with fine.
}

推荐答案

Bjarne Stroustrup编写的C ++编程语言( p. 392,第二版):

The C++ Programming Language by Bjarne Stroustrup (p. 392, 2nd ed.):

15.2.2继承和使用声明
重载解析不适用于不同的类范围(第7.4节)……

15.2.2 Inheritance and Using-Declarations
Overload resolution is not applied across different class scopes (§7.4) …

您可以使用限定名称访问它:

You can access it with a qualified name:

void SomeOtherFunction()
{
  SubClass* test = new SubClass();

  test->Base::Data(1, 1);
}

或通过在 SubClass 中添加using-声明:

or by adding a using-declaration to SubClass:

class SubClass : public Base
{
  public:
  using Base::Data;
  virtual CString& Data( UINT index);
};

void SomeOtherFunction()
{
  SubClass* test = new SubClass();

  test->Data(1, 1);
}

这篇关于为什么我不能使用子类的指针访问基类的公共函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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