C++中的"运算符"错误不匹配
No Match for 'operator' error in C++
#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):#
并且找不到。
我猜你在考虑指针。
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- 如何摆脱C++中的枚举不匹配错误?
- 为什么此代码编译 (C++11) 而没有类型不匹配错误
- C++ sigc::mem_fun 中的“呼叫不匹配”错误
- C++ lambda 函数中的“运算符=不匹配”错误
- C++,与"运算符="不匹配...错误
- 将构造函数添加到boost.python子类导致参数不匹配错误
- 基本代码中的"运算符=不匹配"错误
- 运算符重载,但仍然"与运算符不匹配"错误
- C++ - 模板 + 'using' 子句 - 参数不匹配错误
- 模板模板参数 - 类型/值不匹配错误
- 新建/删除运算符不匹配错误的严重程度
- c++代码中的参数不匹配错误
- 类型值与向量不匹配错误
- C++ 运算符不匹配<<错误
- LNK2038,迭代器不匹配错误,需要忽略
- QT5迁移和Boost:if.hp:宏参数不匹配错误
- x11 xGetImage不匹配错误