在C++中,可以通過重載賦值運(yùn)算符(=)來實(shí)現(xiàn)自定義類型的Assign操作。以下是一個(gè)示例:
#include <iostream>
class MyType {
public:
int value;
MyType(int v) : value(v) {}
// 重載賦值運(yùn)算符
MyType& operator=(const MyType& other) {
if (this != &other) {
value = other.value;
}
return *this;
}
};
int main() {
MyType a(10);
MyType b(20);
std::cout << "Before assignment: " << a.value << " " << b.value << std::endl;
b = a; // 調(diào)用重載的賦值運(yùn)算符
std::cout << "After assignment: " << a.value << " " << b.value << std::endl;
return 0;
}
在上面的示例中,MyType
類重載了賦值運(yùn)算符,當(dāng)進(jìn)行b = a
的操作時(shí),會(huì)調(diào)用重載的賦值運(yùn)算符來實(shí)現(xiàn)自定義類型的Assign操作。