C++中的"运算符"错误不匹配

No Match for 'operator' error in C++

本文关键字:不匹配 错误 运算符 C++ 中的      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <map>
using namespace std;

struct SBLnode {
    string name;
    SBLnode *next;
    SBLnode * left, * right;
};
struct Queue {
    SBLnode * first, * last;
};
typedef SBLnode* BST;

struct SBL {
    Queue q;
    BST root;
};
void SBL_init (SBL& sbl) {
    sbl = NULL;
}

编译时,我不断收到以下错误GCC...

error: no match for ‘operator=’ (operand types are ‘SBL’ and ‘long int’)
  sbl = NULL;
      ^

这个错误基本上是针对行sbl = NULL的,如果有人能向我解释该错误的实际含义,那就太好了。

它找不到SBL &SBL::operator=(const long int &rhs)operator=。有更好的做法。一种选择是使用指针并将其设置为 NULL。NULL 的计算结果为 0。没有运算符将int本质上分配给SBL结构对象。

或者使用初始值定义结构的 const 静态实例,然后在您想要重置变量时将此值分配给变量。

例如:

static const struct SBL EmptyStruct;

这使用静态初始化来设置初始值。

然后,在init中您可以编写:

sbl = EmptyStruct;

注意:必须在 gcc 中使用 -fpermissive 编译或设置EmptyStruct = { } .您必须设置 -fpermissive 的原因在此处列出了 GCC 4.6。GCC 4.4 需要EmptyStruct = { } .

这是您的程序正在运行。最初,它打印"初始"两次,第三次打印空字符串。这意味着,它被 init 函数中的赋值设置为无。

int main() 
{   
    struct SBLnode initial;
    initial.name = "initial";
    struct Queue q;
    q.first = &initial;
    cout << q.first->name << endl;
    struct SBL testInit;
    testInit.q = q;
    SBL_init(testInit);
    cout << testInit.q.first->name << endl;
    return 0;
}

http://ideone.com/Ecm6I9

void SBL_init (SBL& sbl) {
    sbl = NULL;
}

其他人已经指出了为什么这条线不能编译。 也许我可以提出另一种解决方案。 与其提供 init 函数,为什么不给所有结构构造函数提供这样的构造函数呢? 有什么原因你不能提供这些吗? 如果需要指针的浅表复制,则不需要定义运算符 = 和复制构造函数。 由于节点通常需要移动,我猜浅拷贝很好。 如果使用 c++ 11 而不是 0,您当然可以使用 nullptr。 我不是 NULL 宏的忠实粉丝,关于 NULL 的意见经常有所不同。

struct SBL {
    SBL() : root(0) {}
    Queue q;
    BST root;
};
struct Queue {
    Queue() : first(0), last(0) {}
    SBLnode * first, * last;
};

NULL是一个扩展到整数文字0的宏。没有内部或用户定义的运算符可以将整数分配给类型为 SBL 的对象。

看起来你把sbl当作一个指针;但它不是一个指针,它是一个参考。

你可能想写这个:

void SBL_init (SBL& sbl) {
    sbl.root = NULL;
}

这将通过清空其成员指针来初始化sbl

正如其他人所评论的那样,nullptr在C++11中是首选:

void SBL_init (SBL& sbl) {
    sbl.root = nullptr;
}

此错误意味着operator= (函数(未在struct SBL中定义。写作时需要

sbl = NULL;

溶液:

提供SBL& operator=( const long int& i); struct SBL

事实上,我认为您会想要类似的东西SBL& operator=( BST b)

struct SBL {
    Queue q;
    BST root;
    SBL& operator=( BST b) {
      root = b;
      return *this;
    }
};

它试图找到一个具有以下形式的赋值运算符

 SBL &SBL::operator=(const long int &rhs):#

并且找不到。

我猜你在考虑指针。