类内函数
创建了一个名为MyClass的类,并在其中实现了默认构造函数、参数化构造函数、拷贝构造函数、移动构造函数、析构函数、拷贝赋值运算符、移动赋值运算符、成员函数、静态成员函数和友元函数。在主函数中,我们创建了几个类对象,并演示了这些函数的调用和使用。请注意,输出语句被添加到每个函数的实现中,以便在调用时打印出相应的消息,以便我们可以清楚地看到每个函数的调用顺序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 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; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人