假设class X我想要返回内部成员的访问权限:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const …Run Code Online (Sandbox Code Playgroud) 我正在考虑关于const和非const类方法的这个问题.首选答案取自Scott Meyers的Effective C++,其中非const方法是根据const方法实现的.
进一步扩展,如果方法返回迭代器而不是引用,如何减少代码重复?修改链接问题中的示例:
class X
{
std::vector<Z> vecZ;
public:
std::vector<Z>::iterator Z(size_t index)
{
// ...
}
std::vector<Z>::const_iterator Z(size_t index) const
{
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
我不能在const方法方面实现非const方法,因为不使用distance()/ advance()技术就无法直接从const_iterator转换为迭代器.
在这个例子中,因为我们使用std :: vector作为容器,所以实际上可以从const_iterator转换为迭代器,因为它们很可能被实现为指针.我不想依赖于此.有更通用的解决方案吗?