c++ - 如何从双指针获取值?

标签 c++ pointers

我正在尝试打印以下代码返回的值:

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

它返回一个双指针,并打印

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

给出一个内存位置,但是当我尝试

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

我得到了错误

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

如何打印 *grid.GetAgent(j, k) 的值?

下面是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

和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;
}

最佳答案

你需要定义一个函数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++ 不打印 Agent通过魔法,你必须告诉它怎么做。

关于c++ - 如何从双指针获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12895058/

相关文章:

C++ large deque - 程序需要很长时间才能退出?

c - 关于指针

pointers - 当字段是指向 x 的指针时,使用反射设置结构字段的值

c - C 如何计算这个表达式? C指针

c++ - 从静态方法访问非静态成员的工作示例

c - posix线程程序解释?

c++ - 在 std::set 或 std::unordered_set 上保留插入顺序

c++ - 分配 C++ 类成员数据的首选方法是什么?

c++ - 卸载 CEF 崩溃

C++ 函数式 : bind classes method through pointer