访问托管引用的重载运算符时出现编译错误 属性
Compilation error when accessing overloaded operator of managed reference property
我收到编译错误
test.cpp(21) : error C2676: binary '+' : 'Manager ^' does not define
this operator or a conversion to a type acceptable to the predefined
operator
尝试编译以下程序时。
public ref class Managed {};
public ref class Manager {
public:
Manager^ operator += (Managed^ m) { list->Add(m); return this; }
private:
System::Collections::Generic::List<Managed^>^ list;
};
public ref class Foo {
public:
property ::Manager^ Manager {
::Manager^ get() { return manager; }
}
private:
::Manager^ manager;
};
int main() {
Foo^ foo = gcnew Foo;
foo->Manager += gcnew Managed; // Line 21
}
当我用下面的函数替换 main
函数时,程序编译通过。
int main() {
Foo^ foo = gcnew Foo;
Manager^ mgr = foo->Manager;
mgr += gcnew Managed;
}
两者之间的本质区别是什么,使一个编译而另一个不编译?
根据 MSDN documentation,operator+=
不是允许的 C++/CLI 用户定义运算符之一。相反,应该定义 operator+
,编译器会将 +=
翻译成 +
,然后是 =
(赋值)。
如果您将 operator+
添加到 Manager
class,然后将 set(::Manager^)
添加到 Foo::Manager
属性,则第 21 行编译。
我收到编译错误
test.cpp(21) : error C2676: binary '+' : 'Manager ^' does not define this operator or a conversion to a type acceptable to the predefined operator
尝试编译以下程序时。
public ref class Managed {};
public ref class Manager {
public:
Manager^ operator += (Managed^ m) { list->Add(m); return this; }
private:
System::Collections::Generic::List<Managed^>^ list;
};
public ref class Foo {
public:
property ::Manager^ Manager {
::Manager^ get() { return manager; }
}
private:
::Manager^ manager;
};
int main() {
Foo^ foo = gcnew Foo;
foo->Manager += gcnew Managed; // Line 21
}
当我用下面的函数替换 main
函数时,程序编译通过。
int main() {
Foo^ foo = gcnew Foo;
Manager^ mgr = foo->Manager;
mgr += gcnew Managed;
}
两者之间的本质区别是什么,使一个编译而另一个不编译?
根据 MSDN documentation,operator+=
不是允许的 C++/CLI 用户定义运算符之一。相反,应该定义 operator+
,编译器会将 +=
翻译成 +
,然后是 =
(赋值)。
如果您将 operator+
添加到 Manager
class,然后将 set(::Manager^)
添加到 Foo::Manager
属性,则第 21 行编译。