问题描述
- const成员函数内将该类的数据成员变成const?
-
#include
using namespace std;
class A
{
public:
void action()
{
cout << "Action in class A!" << endl;
}
};
class B
{
A a;
int s;
public:
void action()
{
cout << "Action in class B!" << endl;
}
A operator->() const
{
return &a;
}
};
class C
{
B b;
public:
void action()
{
cout << "Action in class C!" << endl;
}
B operator->() const
{
return b;
}
};
int main()
{
C *pc = new C;
pc->action();
C c;
c->action();
return 0;
}
在class B中重载->函数被定义为const的。报错说const A不能转换为A*
解决方案
A operator->() const
{
return &a;
}
修改为:
A* operator->()
{
return &a;
}
时间: 2024-09-25 01:23:18