1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++で文字列クラスStringでイコールオペレータを実装してみた

Posted at

概要

C++で文字列クラスを実装してみました。イコールオペレータを実装してみました。以下のページを参考にしました。
http://wisdom.sakura.ne.jp/programming/cpp/cpp27.html

ソースコード

string3.cpp
#include<iostream>

class String {
private:
  char* m_data;
  int m_size;
public:
  String(){
    m_data = new char[1];
    m_data[0] = '\0';
    m_size = 1;
  }
  void ShowData(){
    std::cout << "==>> ShowData" << std::endl;
    std::cout << m_data << std::endl;
  }
  void SetData(char *data){
    m_data = data;
    int i = 0;
    while( m_data[i] != '\0' ) i++;
    m_size = i+1;
  }
  char *GetData(){
    return m_data;
  }
  int GetSize(){
    return m_size;
  }
  void SetData(const char *data){
    m_data = (char *)data;
  }
  char GetData(int index){
    return m_data[index];
  }
  String operator = (char *str){
    this->m_data = str;
    return *this;
  }
  String operator = (const char *str){
    this->m_data = (char *)str;
    return *this;
  }
};

int main(){
  String str;
  str.ShowData();
  char data1[10] = "abcd";
  str.SetData(data1);
  str.ShowData();
  str.SetData("1234");
  str.ShowData();
  String str1, str2;
  str1 = str2 = "abcdefg";
  str1.ShowData();
  str2.ShowData();
  return 0;
}

コンパイル

以下のコマンドを実行しました。

$ g++ string3.cpp

実行結果

以下のコマンドを実行しました。

$ ./a.out 
==>> ShowData

==>> ShowData
abcd
==>> ShowData
1234
==>> ShowData
abcdefg
==>> ShowData
abcdefg

まとめ

次はプラスオペレータを実装してみようと思っています。
何かの役に立てばと。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?