C++构造函数 拷贝赋值

xiaoxiao2026-05-17  11

class MyString { public: MyString(); MyString(int newsize); MyString(const MyString& ms); const MyString& operator=(const MyString& ms); virtual ~MyString(); private: int *ptr; int size; }; / MyString::MyString(int newsize) { size = newsize; ptr = new int[size]; for(int i=0; i < size; i++){ ptr[i] = 0; } cout<<"construct is executing size is "<<size<<endl; } MyString::MyString(const MyString& ms){ size = ms.size; ptr = new int[size]; for(int i = 0; i < size ; i++){ ptr[i] = ms.ptr[i]; } cout<<"copy construct is executing.."<<"address of ptr is "<<ptr<<endl; } const MyString& MyString::operator=(const MyString& ms){ cout<<"operator is executing"<<endl; if(this != &ms){ delete[] ptr; size = ms.size; ptr = new int[size]; for(int i = 0; i < size ; i++){ ptr[i] = ms.ptr[i]; } return *this; } } MyString::~MyString() { cout<<"desturct address of ptr is "<<ptr<<endl; delete[] ptr; } MyString play(MyString a) { return a; } int main(int argc, char* argv[]) { //printf("Hello World!\n"); /*testint t1 = play(4); testint t2 = play(5); testint t3 = play(t1);*/ MyString ms1 = MyString(5); MyString ms2 = play(ms1); return 0; } 输出结果: [img]/upload/attachment/105992/ff084db7-b188-3bba-8151-3b1a9d8fca3c.bmp[/img] 注意将play(ms1)的返回值赋值给ms2,执行拷贝函数。然后返回值再析构
转载请注明原文地址: https://www.6miu.com/read-5048905.html

最新回复(0)