c++面向對象高級編程 學習二 帶指針的類

帶指針的類,必須要自己寫拷貝構造和賦值構造
拷貝構造:參數和類的類型一樣的構造函數
賦值構造:重寫操作符=,且其參數和類的類型一樣

class String
{
public:
String(const char* cstr = 0);
String(const String& str);
String& operator=(const String& str);
~String();
char* get_c_str() const { return m_data; }
private:
char* m_data;
};
1

傳入字符指針,構建字符的長度,將數據拷貝進m_data中。
當沒有傳入字符指針時,將m_data置為‘\0’。

inline
String::String(const char* cstr = 0)
{
if (cstr) {
m_data = new char[strlen(cstr)+1];
strcpy(m_data, cstr);
}
else { //  未指定初值
m_data = new char[1];
*m_data = '\0';
}
}

拷貝構造的具體實現方式:將str中的數據拷貝進m_data中。

inline
String::String(const String& str)
{
m_data = new char[ strlen(str.m_data) + 1 ];
strcpy(m_data, str.m_data);
}

賦值構造的具體實現方式:首先檢測自我賦值,若不進行檢測的話,當是自我賦值的時候,將內存釋放,則賦值和被賦值的指針都會釋放,使得最后不能構造成功。
若不是自我賦值,則釋放m_data的內存,并將str的數據復制到m_data中

inline
String& String::operator=(const String& str)
{
if (this == &str)  //注意自我賦值return *this;delete[] m_data;
m_data = new char[ strlen(str.m_data) + 1 ];
strcpy(m_data, str.m_data);
return *this;

析構函數的實現:釋放指針指向的內存

inline
String::~String()
{
delete[] m_data;
}

MyString.h文件如下:
此處將類的聲明和實現寫在了一塊

#ifndef __MYSTRING__
#define __MYSTRING__#include<iostream>
#include<cstring>
using namespace std;class MyString {
public:MyString(const char* );MyString(const MyString & str);MyString& operator =(const MyString& str);~MyString();char* get_c_str() const { return m_data; }private:char* m_data;
};
MyString::MyString(const char* cstr = 0) {if (cstr) {m_data = new char[strlen(cstr)+1];strcpy(m_data,cstr);}else {m_data = new char[1];*m_data = '\0';}
}
MyString::MyString(const MyString & str) {m_data = new char[strlen(str.get_c_str())+1];strcpy(m_data,str.get_c_str());
}MyString& MyString::operator =(const MyString& str) {if (this == &str)return *this;delete[]m_data;m_data = new char[strlen(str.get_c_str()) + 1];strcpy(m_data, str.get_c_str());return *this;
}
MyString::~MyString() {delete[]m_data;
}ostream& operator <<(ostream& os, const MyString& str) {return os << "我的string:"<<str.get_c_str() << endl;
}
#endif

測試文件如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>#include "MyString.h"
#include<cstring>
using namespace std;void main() {MyString s1 = "hello";MyString s2=s1;MyString s3(s1);cout << "s1:"<<s1 << endl;cout << "s2:" << s2 << endl;cout << "s3:" << s3 << endl;
}

輸出結果如下:
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/446631.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446631.shtml
英文地址,請注明出處:http://en.pswp.cn/news/446631.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

英語口語 week11 Tuesday

英語文章 It was a cold and gloomy winter afternoon, people with their chilled hands tucked into their pockets or hidden in their sleeves. Fred was in a depressed mood, just like the weather,for he failed to get any award in the debate competition When he …

codeforces 271A-C語言解題報告

271A題目網址 題目解析 1.輸入一個年份,求這個年份之后的每一個數字都各不相同的年份 舉例: 輸入: 2013 輸出: 2014 2.求年份(四位數)的每一位數,再把這些數逐個比較 四位數求: 千位:n/1000 百位:n%1000/100 十位:n%100/10 個位:n%10/1; 代碼 #include<stdio.h> #in…

進程之間通信 共享內存

命令 ipcs 命令查看共享內存、消息隊列、管道等相關信息ipcs -m 查看共享內存的信息代碼 創建共享內存共享內存 關聯 進程分離共享內存刪除共享內存 #include <sys/shm.h> #include <iostream>#define BUF_SIZE 1024int main() {int share_id 0;//創建共享內存i…

c++面向對象高級編程 學習三 堆、棧和內存泄漏

棧&#xff0c;是存在于某作用域的一塊內存空間。在函數體內聲明的任何變量&#xff0c;其所使用的內存空間均來自于棧。 堆&#xff0c;是指由操作系統提供的一塊global內存空間&#xff0c;程序可動態分配獲得若干內存空間塊。 new操作符生成的對象所占用的內存空間即是從堆中…

clion編寫C++ 使用多線程時候,CMakeLists.txt書寫,引用-pthread

添加如下一行 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") 具體的例子 cmake_minimum_required(VERSION 3.17) project(mutex_learn)set(CMAKE_CXX_STANDARD 14)set(BOOST_ROOT "/usr/local/include/boost") #添加頭文件搜索路徑 include_direc…

codeforces 677A-C語言解題報告

677A題目網址 題目解析 1.輸入n個數字,如果輸入的數字比h大,就加2,如果小于等于h,就加1 舉例: 輸入: 3 7 4 5 14 輸出: 4 代碼 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int main() { int n0,h0,count0;int nu…

c++面向對象高級編程 學習四 靜態、類模板、函數模板

靜態static&#xff1a;靜態數據和靜態函數&#xff0c;在內存中只有一份&#xff0c;不會隨著創建對象的數目的增加而增加 static數據&#xff1a;比如銀行的account類中&#xff0c;賬戶名是普通數據&#xff0c;100個對象會有100個賬戶名&#xff0c;但利率都是相同的&#…

線程的編程

完整代碼 #include <sys/shm.h> #include <iostream> #include <unistd.h> #include <pthread.h>void * child1(void *arg){pthread_t tid pthread_self();printf("1 thread %lu \n",tid);}int main(int argc,char* argv[]) {int result{…

英語口語 week11 Friday

英語文章 I very much like simplicity in life. For me, college is far more than a place to improve my intellectual abilities Every weekend, I usually have a walk along the way to the front gate of Mount Qingcheng, enjoying the intense aromas of flowers on …

c++面向對象高級編程 學習五 組合、委托與繼承

組合 composition 表示has a queue類中有一個deque容器&#xff0c;這種關系叫做 組合 queue中的六個函數都是調用c的函數完成的 template <class T> class queue { ... protected: deque<T> c; // 底層容器 public: // 以下完全利用 c 的操作函數完成 bool empt…

C++四種類型轉換運算符:static_cast、dynamic_cast、const_cast和reinterpret_cast

參考鏈接 C四種類型轉換運算符&#xff1a;static_cast、dynamic_cast、const_cast和reinterpret_cast

英語口語 week12 WednesDay

英語文章 Chengdu, a city with a long history, has always enjoyed the reputation as " The Land of Abundance" . It has been noted as one of the most livable cities in China, partly resulting from its favorable natural conditions and wealthy produc…

c++面向對象高級編程 學習六 虛函數

虛函數&#xff1a;在成員函數前面加上virtual&#xff0c;函數就變成了虛函數 繼承函數&#xff1a;子類可以調用父類的函數&#xff0c;叫做繼承了函數&#xff0c;即函數的調用權 三種函數&#xff1a; non-virtual 函數&#xff1a; 你不希望 derived class 重新定義 (ov…

C++ 數據結構 線性鏈表

#pragma once 減少頭文件組合&#xff0c;降低編譯出錯的概率作用等效于 #ifndef FUNC_H #define FUNC_H代碼主體#endif 線性表的定義 排隊問題 簡單的線性表 (物理 或者邏輯結構)1&#xff0c;數組2&#xff0c;鏈表線性表相關操作&#xff1a;1&#xff0c;線性表初始化2&a…

英語口語 week12 Thursday

英語文章 As the pace of life quickens with technological advancements, people are occupied by all kinds of trivial matters. They seem forever on the go. There’s no difficulty in imagining that the hustle and bustle of everyday life can make us lose focus…

H.264/AVC視頻編解碼技術詳解 第一章 視頻信息與壓縮編碼

H.264/AVC視頻編解碼技術詳解系列筆記 是對 H.264/AVC視頻編解碼技術詳解 課程的學習 文章目錄人與世界的交互視頻信號的表示方法視頻壓縮編碼視頻信息為什么可以被壓縮&#xff1f;視頻壓縮編碼的分類&#xff1a;視頻壓縮編碼的基本技術人與世界的交互 從遠古時代開始&#…

英語口語 week13 Monday

英語文章 Competitions between businesses can be very aggressive in contemporary society. However, the competition for talented personnel is thought to be the key to business competition. Wise employers consider their employees as the company’s core asset…

文件系統的由來

啟蒙篇 文件的由來 磁盤上保存的是一對十六進制的數據&#xff0c;如何切分數據形成不同的文件&#xff0c;也就是如何確定一個文件的起始和終止位置&#xff1f;將相關數據打包在一起形成一個文件&#xff0c;比如從什么位置開始到什么位置結束&#xff0c;是一張圖片、一段…

c++面向對象高級編程 學習七 轉換函數

轉換函數&#xff1a;對象A和對象B之間的互相轉換。 class Fraction { public:Fraction(int num,int den1):m_numerator(num),m_denominator(den){}operator double()const{return (double)(m_numerator/m_denominator);} private:int m_numerator; //分子int m_denominator;/…

英語口語 week13 Wednesday

英語文章 Despite his extraordinary success in writing fairy tales,Hans Christian Andersen preferred to living in a way of simplicity and frugality. He often wore an old hat when he went out. One day, a well-dressed man stopped Andersen on the street, inte…