解决使用重载运算符时的临时错误

Taking adress of temporary error while using overloaded operator

本文关键字:错误 运算符 重载 解决      更新时间:2023-10-16

我的c ++项目中有一个字符串类。我必须使用双链表并创建自己的字符串类。在我的字符串类中,我必须重载<>==运算符。实际上我做到了。但是在我的另一个类中,我有一个列表函数来比较我的字符串类。在这个比较中,我遇到了"临时地址"错误。

这是我的字符串类:

#include "String.h"
String::String(int coming)
{
   x=coming;
}
int  String::getX()
{
    return x;
}
String String::operator==(String *taken)
{
    return String (x==taken->x);
}

这是我的上市方法:

void myclass::list(String *taken)
{
    otherclass *temp=head;
    while(temp!=NULL)
    {
        if(&temp->get_string()==taken)//where i get error message.
            cout<<temp<<endl;
        temp=temp->get_nextnode();
    }
}

编译器准确地告诉你问题:你不能获取临时对象的地址。 temp->get_string()是一个临时对象1,并且您正在尝试获取其地址。

我不太确定你在这里的目的是什么,所以我不能建议修复。 但我强烈建议将String::operator==定义为将指针定义为右侧会导致混淆。 让它再返回一次String也毫无意义;通常,人们会期望==的计算结果为布尔值。


1.嗯,大概。 您尚未显示get_string()声明.