在类中定义一个int变量和vector容器,并对其进行拷贝构造,+运算符重载,=运算符重载,输出流运算符重载,自增运算符重载操作
时间: 2024-06-15 21:07:16 浏览: 98
在类中定义一个int变量和vector容器,并对其进行拷贝构造、+运算符重载、=运算符重载、输出流运算符重载和自增运算符重载操作的示例代码如下:
```cpp
#include <iostream>
#include <vector>
class MyClass {
private:
int myInt;
std::vector<int> myVector;
public:
// 构造函数
MyClass(int num, const std::vector<int>& vec) : myInt(num), myVector(vec) {}
// 拷贝构造函数
MyClass(const MyClass& other) : myInt(other.myInt), myVector(other.myVector) {}
// +运算符重载
MyClass operator+(const MyClass& other) {
int sum = myInt + other.myInt; std::vector<int> resultVec = myVector;
resultVec.insert(resultVec.end(), other.myVector.begin(), other.myVector.end());
return MyClass(sum, resultVec);
}
// =运算符重载
MyClass& operator=(const MyClass& other) {
if (this != &other) {
myInt = other.myInt;
myVector = other.myVector;
}
return *this;
}
// 输出流运算符重载
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "myInt: " << obj.myInt << ", myVector: [";
for (int i = 0; i < obj.myVector.size(); ++i) {
os << obj.myVector[i];
if (i != obj.myVector.size() - 1) {
os << ", ";
}
}
os << "]"; return os;
}
// 自增运算符重载
MyClass& operator++() {
++myInt;
for (int i = 0; i < myVector.size(); ++i) {
++myVector[i];
}
return *this;
}
};
int main() {
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = {4, 5, 6};
MyClass obj1(10, vec1);
MyClass obj2(20, vec2);
// 拷贝构造
MyClass obj3 = obj1;
// +运算符重载
MyClass obj4 = obj1 + obj2;
// =运算符重载
obj3 = obj4;
// 输出流运算符重载
std::cout << obj3 << std::endl;
// 自增运算符重载
++obj3;
std::cout << obj3 << std::endl;
return 0;
}
```
阅读全文