类内函数
创建了一个名为MyClass的类,并在其中实现了默认构造函数、参数化构造函数、拷贝构造函数、移动构造函数、析构函数、拷贝赋值运算符、移动赋值运算符、成员函数、静态成员函数和友元函数。在主函数中,我们创建了几个类对象,并演示了这些函数的调用和使用。请注意,输出语句被添加到每个函数的实现中,以便在调用时打印出相应的消息,以便我们可以清楚地看到每个函数的调用顺序
class MyClass {
public:
int value;
// Default constructor
MyClass() {
value = 0;
cout << "Default constructor called" << endl;
}
// Parameterized constructor
MyClass(int val) {
value = val;
cout << "Parameterized constructor called" << endl;
}
// Copy constructor
MyClass(const MyClass& other) {
value = other.value;
cout << "Copy constructor called" << endl;
}
// Move constructor
MyClass(MyClass&& other) noexcept {
value = other.value;
cout << "Move constructor called" << endl;
}
// Destructor
~MyClass() {
cout << "Destructor called" << endl;
}
// Copy assignment operator
MyClass& operator=(const MyClass& other) {
if (this != &other) {
value = other.value;
}
cout << "Copy assignment operator called" << endl;
return *this;
}
// Move assignment operator
MyClass& operator=(MyClass&& other) noexcept {
value = other.value;
cout << "Move assignment operator called" << endl;
return *this;
}
// Member function
void printValue() {
cout << "Value: " << value << endl;
}
// Static member function
static void staticFunction() {
cout << "Static function called" << endl;
}
// Friend function
friend void friendFunction(const MyClass& obj);
};
void friendFunction(const MyClass& obj) {
cout << "Friend function called. Value: " << obj.value << endl;
}
int main()
{
MyClass obj1; // Default constructor called
obj1.value = 10;
MyClass obj4(20);
MyClass obj2(obj1); // Copy constructor called
MyClass obj3 = std::move(obj4); // Move constructor called
obj2 = obj3; // Copy assignment operator called
obj3 = std::move(obj2); // Move assignment operator called
obj3.printValue(); // Value: 10
MyClass::staticFunction(); // Static function called
friendFunction(obj3); // Friend function called. Value: 10
return 0;
}

浙公网安备 33010602011771号