5
7

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 5 years have passed since last update.

[C⇒C++] 構造体同士の比較演算 operator

Last updated at Posted at 2018-03-15

Cでは構造体同士を比較演算子'=='や'!='で比較することはできません。
C++ではoperatorを使うことで構造体同士を演算子で比較することができます。

サンプルコード・・・コマンドで与えられた名前とIDが従業員と一致するか判定し、新人かどうか比較する

まずはCで書いたコード。

SampleC.c
#include <stdio.h>
#include <string.h>

typedef struct guy_st
{
  const char* name;
  const char* id;
}GUY_ST;

static GUY_ST Set_struct(const char* name, const char* id)
{
  GUY_ST Guy;
  Guy.name = name;
  Guy.id = id;
  return Guy;
}

static int Guy_equal(GUY_ST employee, GUY_ST newguy)
{
  return (!strcmp(employee.name, newguy.name) &&
	  !strcmp(employee.id, newguy.id));
}

int main(int argc, char *argv[])
{
  GUY_ST employee = Set_struct("JohnSmith", "A0001");
  GUY_ST newGuy = Set_struct(argv[1], argv[2]);

  if (Guy_equal(employee, newGuy))
  {
    printf("You are not new.\n");
  }
  else
  {
    printf("Welcome new guy.\n");
  }

  return 0;
}

次はC++で書いたコード。

SampleC++.cpp
#include <iostream>
#include <string>

using namespace std;

struct Guy_St
{
  std::string name;
  std::string id;

  Guy_St(std::string name, std::string id)
     :name(name),
      id(id)
  {
  }

  bool operator==(const Guy_St& rhs) const
  {
     return (name == rhs.name &&
             id == rhs.id);
  }
};

int main(int argc, char *argv[])
{
  Guy_St employee("JohnSmith", "A0001");
  Guy_St newGuy(argv[1], argv[2]);

  if (employee == newGuy)
  {
      std::cout << "You are not new." << "\n";
  }
  else
  {
      std::cout << "Welcome new guy." << "\n";
  }

  return 0;
}

構造体の中に構造体メンバの初期化処理と比較処理があることと、
比較演算子でif文を作ることができていることでリーダブル性が向上しました。

出力結果

$ gcc SampleC.c
$ ./a.out JohnSmith A0001
You are not new.
$ ./a.out JohnSmith A0002
Welcome new guy.

$ g++ -std=c++11 SampleC++.cpp
$ ./a.out JohnSmith A0001
You are not new.
$ ./a.out JohnSmith A0002
Welcome new guy.
5
7
5

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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?