简体   繁体   中英

Return a const reference and non const member function call

I am a novice C++ programmer trying to hone my skills on a pet project and i have the following problem.

I have a class named System that contains a single Object of another class Agent. I would like an external source to call the methods of the Agent class object in the following manner:

system.agent().exploration(3.0);

Where exploration(3.0) sets an internal variable of agent to 3.0. In order to do this i return the Agent object by reference:

Agent& agent() {return agent;}

Although this works, it is still possible for someone to change the agent as followed:

system.agent() = Agent(1.0,2.0);

In my case this is unwanted behavior. To fix this is figured i could return Agent as const reference:

const Agent& agent() {return agent;}

However this code doesn't compile as the method exploration(float e) is non-const (it modifies an internal variables of the agent object).

What is the right way to make the agent object public interface available to the outside world through the System class without allowing someone to completely replace the agent object?

You could write a function in your System class that wraps the Agent function.

class System
{
private:
    Agent agent;
public:
    void exploration(float num) { agent.exploration(num); }
    //...
};

If you don't want to allow copying, you should implement your own overloaded assignment operator under private but without implementing it. This will not allow the compiler to create it's own assignment operator, thus not allowing the copying.

There are many possible solutions : working with the class agent, modifying the operator= of agent, if you don't need the getter then only implement a exploration method in system.

However I would suggest you implement your explorator as a visitor , it is best practice when you have to dispatch to sub objects, it's very easy to implement,you can get a nice interface by overloading operator() and it spares you from duplicating code when you have many different actions to do on sub objects. http://en.wikipedia.org/wiki/Visitor_pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM