【问题标题】:Returning an address in a pointer in a string function在字符串函数的指针中返回地址
【发布时间】:2019-09-15 20:28:18
【问题描述】:

我正在编写一组具有特定要求的链表函数。我必须编写一个具有以下要求的函数

string retrieve_front (llheader)
retrieves the contents of the node at the front. Does not remove the node. If the list is empty, throws an exception.

用这个结构定义

struct LLnode
{
    LLnode * fwdPtr; // has a pointer member
    string theData; // the data within the node
};

我真的想返回第一个节点的十六进制地址以及其中的数据,我现在想知道这是可能的

string retrieve_front(LLnode * theLLHeader)
{
    string data, report;

    if (theLLHeader == nullptr)
    {
        throw "This list is empty";
    }
    else
    {
        data = theLLHeader -> theData;
        report = "Front_Node[address: " + theLLHeader + " data: " + data + "]\n";
        return report;
    }
}

这给出了以下错误消息:

../test.cpp:103:35: error: invalid operands to binary expression ('const char *' and 'LLnode *')
                report = "Front_Node[address: " + theLLHeader + " data: " + data + "]\n";
                         ~~~~~~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~

我知道指针不是字符串(尽管它与 cout 在不同的函数中效果很好)。我尝试使用static_cast 无济于事,并且在搜索谷歌时看到了一些相关问题,但无法理解答案。有没有一种简单的方法来解决这个问题,还是我应该坚持单独返回数据,这已经是一个字符串?

【问题讨论】:

标签: c++ pointers


【解决方案1】:

这里是你的函数的修改版本。

string retrieve_front(LLnode * theLLHeader) {

string data, report;

if (theLLHeader == nullptr)
{
    throw "This list is empty";
}
else
{
    data = theLLHeader -> theData;
    stringstream ss;
    ss << theLLHeader ;
    report = "Front_Node[address: " + ss.str() + " data: " + data + "]\n";
    return report;
}

}

【讨论】:

    【解决方案2】:

    您可以使用 stringstream 来实现这一点。在您的函数中添加以下行。

    std::stringstream ss;
    ss << "Front_Node[address: " << static_cast<const void*>(theLLHeader) << " data: " << data << "]\n";
    report = ss.str();
    return report;
    

    注意:不要忘记包含#include&lt;sstream&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2015-12-02
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      相关资源
      最近更新 更多