【问题标题】:How to make two functions with same names in Base class?如何在基类中创建两个具有相同名称的函数?
【发布时间】:2015-06-26 00:57:08
【问题描述】:

此代码已编译。

struct A
{
    const int *getX() const
        {
            return &x;
        }

    int *getX()
        {
            const A *thisConst = this;
            return const_cast<int *>(thisConst->getX());
        }


    void f()
        {
            int *p = getX();
        }

    int x;
};

但这段代码没有。

struct I
{
    virtual const int *getX() const = 0;

    int *getX()
        {
            const I *thisConst = this;
            return const_cast<int *>(thisConst->getX());
        }
};

struct A : I
{
    virtual const int *getX() const
        {
            return &x;
        }

    void f()
        {
            int *p = getX();
        }

    int x;
};

'const_cast' : 无法从 'const int *' 转换为 'int *'

我知道,如果我给出不同的名称,它将被编译。但是有没有不重命名函数的方法?

【问题讨论】:

  • 您的标题似乎与您的问题不一样...您可以更改两者之一以避免混淆吗?另外,您到底想在这里实现什么?
  • 我想在不重命名getX的情况下编译这段代码。

标签: c++ inheritance overloading virtual-functions


【解决方案1】:

'const_cast' : 无法从 'const A *' 转换为 'int *'

我在尝试编译您的程序时没有收到此错误,而是收到了

error: invalid conversion from 'const int*' to 'int*' [-fpermissive]

为了编译成功,我更正了以下行

int *p = getX();

const  int *p = getX(); 

const int *int* 是两种不同的类型,不能不强制转换直接赋值或修改变量p 的类型。

【讨论】:

  • 我做了一些修改。我知道const T *T * 之间的区别。但我需要能够得到T *,因为我在这个问题中用int 替换的对象调用不是const 方法。
  • @Ufx 如果您编辑它作为附加说明,而不是更改发布的问题。我不知道你编辑了什么。
  • 在此处查看编辑问题的示例:stackoverflow.com/questions/31063331/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 2011-05-29
相关资源
最近更新 更多