c++ - 如何在基类中创建同名的两个函数?

标签 c++ inheritance overloading virtual-functions

此代码已编译。

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 *”

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

最佳答案

'const_cast' : cannot convert from 'const A *' to 'int *'

我在尝试编译你的程序时没有得到这个错误,而是我得到了

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

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

int *p = getX();

const  int *p = getX(); 

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

关于c++ - 如何在基类中创建同名的两个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31063226/

相关文章:

c++ - 将结构中的信息写入文件

c++ - 如何在 C++ 中使用 << 将 unsigned/signed char 或 <cstdint> 类型输出为整数

c# - 在 C# oop 中如何解释为什么基类可以采用派生类实例

java - 使用可变参数重载时方法不明确

c++ - 运算符 () 重载模板 C++

C#重载问题

c++ - 包含相同类型的结构指针的结构指针的初始化

c++ - 如何将整数传递给 CreateThread()?

c# - 如何确定给定类型 (System.Type) 是否继承自特定基类(在 .Net 中)?

Java - 从接受泛型的类继承?