首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从双指针中获取值?

如何从双指针中获取值?
EN

Stack Overflow用户
提问于 2012-10-15 19:50:47
回答 1查看 1.5K关注 0票数 0

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

代码语言:javascript
复制
Agent** Grid::GetAgent(int x, int y)
{
    return &agents[x][y];
}

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

代码语言:javascript
复制
std::cout << *grid.GetAgent(j, k) << endl;  

给出了内存位置,但当我尝试

代码语言:javascript
复制
std::cout << **grid.GetAgent(j, k) << endl; 

我得到了错误

代码语言:javascript
复制
main.cpp:53: error: no match for ‘operator<<’ in ‘std::cout << * * grid.Grid::GetAgent(j, k)’

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

下面是Agent.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-15 19:56:53

您需要定义一个函数ostream& operator<<(ostream&, const Agent&)

代码语言:javascript
复制
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,您必须告诉它是如何打印的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12895058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档