为什么g ++会说'不匹配'运算符=',当有明显的情况时,Visual Studio可以看到有?

pdu*_*sen 6 c++ compiler-errors g++ operators

我正在编写一个接口库,允许在类型的对象中访问表中的变量(理论上无限深度)regula::State.我通过operator[]在类中重载来完成此操作,然后返回该类的另一个类,并operator[]根据需要再次调用.例如:

regula::State t;
t["math"]["pi"] = 3.14159;
Run Code Online (Sandbox Code Playgroud)

以上应该将值放在表中的3.14159变量pimath.基本上,它通过t返回一个代理对象来执行此操作,该代理对象math返回另一个代表pi我们实际保存变量的代理对象.这个内部与问题无关,但这里是函数头.

LObject LObject::operator[] (const std::string name);
Run Code Online (Sandbox Code Playgroud)

基本上,在上面的例子中,程序应该使用字符串调用t's 并返回另一个对象,然后使用返回最终对象的字符串调用该对象,然后使用该字符串将值赋给该对象.operator[]"math"operator[]"pi"operator=

template <typename T>
T LObject::operator= (const T& value);
Run Code Online (Sandbox Code Playgroud)

T返回的只是一个副本value通过.

现在,我的代码在Visual C++ 2008中产生NO错误并且工作正常.但是当我尝试在Linux上编译它时g++,我收到以下错误:

../../test/regula-test.cpp:100: error: no match for ‘operator=’ in 
‘L.regula::State::operator[](std::basic_string<char, std::char_traits<char>, 
std::allocator<char> >(((const char*)"Numbers"), ((const std::allocator<char>&)((const 
std::allocator<char>*)(& std::allocator<char>()))))) = Numbers’
../../include/regula.hpp:855: note: candidates are: regula::LObject&
 regula::LObject::operator=(const regula::LObject&)
Run Code Online (Sandbox Code Playgroud)

出于某种原因,g++似乎是试图调用operator=operator[]像它应该是,而不是返回的对象.

实际上,我可以通过更换返回类型修复这个错误operator=void:

template <typename T>
/*T*/ void LObject::operator= (const T& value);
Run Code Online (Sandbox Code Playgroud)

但这不是优选的,此外,我在其他几个位置有类似的错误,类似的重载operator==:

../../test/regula-test.cpp:153: error: no match for ‘operator==’ in ‘pi == 
L.regula::State::operator[](std::basic_string<char, std::char_traits<char>, 
std::allocator<char> >(((const char*)"pi"), ((const std::allocator<char>&)((const 
std::allocator<char>*)(& std::allocator<char>())))))’
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这个错误在g ++中发生,或者为什么它不在Visual C++中发生.任何人都可以对此有所了解或推荐任何解决方案?

Pot*_*ter 6

ISO标准的第5.17节说

有几个赋值运算符,所有赋值运算符都从右到左分组.所有都需要一个可修改的左值作为左操作数,赋值表达式的类型是其左操作数的类型.赋值操作的结果是赋值发生后存储在左操作数中的值; 结果是一个左值.

你的operator=回报不仅是错误的类型,甚至也不是左值.假设GCC的错误消息不包括任何其他候选者operator=(const regula::LObject&),GCC完全忽略了你的过载.将operator=它提到是默认的,自动生成功能.

乍一看,你operator[]也应该返回一个参考.如上所述,没有像你的例子那样的赋值表达式应该可以工作.

所以,你应该有功能

LObject &LObject::operator[] (const std::string name);
Run Code Online (Sandbox Code Playgroud)

template <typename T>
LObject &LObject::operator= (const T& value);
Run Code Online (Sandbox Code Playgroud)