Niek de Klein
Niek de Klein

Reputation: 8824

How to get the value from a double pointer?

I'm trying to print the value returned by the following code:

Agent** Grid::GetAgent(int x, int y)
{
    return &agents[x][y];
}

It returns a double pointer, and printing

std::cout << *grid.GetAgent(j, k) << endl;  

gives a memory locations, but when I try

std::cout << **grid.GetAgent(j, k) << endl; 

I get the error

main.cpp:53: error: no match for ‘operator<<’ in ‘std::cout << * * grid.Grid::GetAgent(j, k)’

How can I print the value from *grid.GetAgent(j, k)?

Below is the Agent.h

#ifndef AGENT_H
#define AGENT_H


enum AgentType { candidateSolution, cupid, reaper, breeder};

class Agent
{
public:
    Agent(void);
    ~Agent(void);

    double GetFitness();
    int GetAge();
    void IncreaseAge();
    AgentType GetType();
    virtual void RandomizeGenome() = 0;

protected:
    double m_fitness;
    AgentType m_type;
private:
    int m_age;
};

#endif // !AGENT_H

and Agent.cpp

#include "Agent.h"


Agent::Agent(void)
{
    m_age = 0;
    m_fitness = -1;
}


Agent::~Agent(void)
{
}

int Agent::GetAge()
{
    return m_age;
}

double Agent::GetFitness()
{
    return m_fitness;
}

void Agent::IncreaseAge()
{
    m_age++;
}

AgentType Agent::GetType()
{
    return m_type;
}

Upvotes: 0

Views: 1696

Answers (1)

john
john

Reputation: 8027

You need to define a function ostream& operator<<(ostream&, const Agent&)

ostream& operator<<(ostream& out, const Agent& x)
{
  // your code to print x to out here, e.g.
  out << (int)x.GetType() << ' ' << x.GetFitness() << ' ' << x.GetAge() << '\n';
  return out;
}

C++ does not print Agent by magic, you have to tell it how.

Upvotes: 5

Related Questions