在我正在编写的程序中出现了以下模式.我希望它不是太做作,但它设法Foo在const方法中改变一个对象Foo::Questionable() const,而不使用任何const_cast或类似的东西.基本上,Foo存储参考FooOwner,反之亦然,并在Questionable(),Foo设法修改本身在一个const方法通过调用mutate_foo()关于它的主人.问题遵循代码.
#include "stdafx.h"
#include <iostream>
using namespace std;
class FooOwner;
class Foo {
FooOwner& owner;
int data;
public:
Foo(FooOwner& owner_, int data_)
: owner(owner_),
data(data_)
{
}
void SetData(int data_)
{
data = data_;
}
int Questionable() const; // defined after FooOwner
};
class FooOwner {
Foo* pFoo;
public:
FooOwner()
: pFoo(NULL)
{}
void own(Foo& foo)
{
pFoo = &foo;
}
void mutate_foo()
{
if …Run Code Online (Sandbox Code Playgroud)