此代码已编译。
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/