Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created July 11, 2021 04:43
Show Gist options
  • Save shiracamus/82132d85574c5abec90162077a06410d to your computer and use it in GitHub Desktop.
Save shiracamus/82132d85574c5abec90162077a06410d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
// 構造体はデータ定義。処理関数は別定義。他と同じ関数名にならないよう気を使う
typedef struct {
const char *name;
} StructDrink;
void ask_more(StructDrink *drink) {
std::cout << drink->name << "をもう一杯いかが?" << std::endl;
}
// クラスはデータ定義と処理関数が一体。他と同じ関数名でも別関数になる
class ClassDrink {
public:
const char *name;
ClassDrink(const char *name) {
this->name = name;
}
void ask_more() {
std::cout << this->name << "をもう一杯いかが?" << std::endl;
}
};
void local_access() {
StructDrink struct_drink = { .name = "コーラ" };
ClassDrink class_drink = ClassDrink("コーヒー");
std::cout << "local struct: " << struct_drink.name << std::endl;
std::cout << "local class: " << class_drink.name << std::endl;
ask_more(&struct_drink);
class_drink.ask_more();
}
void object_access() {
StructDrink *malloc_drink = (StructDrink *)malloc(sizeof(StructDrink));
malloc_drink->name = "オレンジジュース";
ClassDrink *instance_drink = new ClassDrink("バナナジュース");
std::cout << "malloc object: " << malloc_drink->name << std::endl;
std::cout << "instance object: " << instance_drink->name << std::endl;
ask_more(malloc_drink);
instance_drink->ask_more();
free(malloc_drink);
delete instance_drink;
}
int main()
{
local_access();
object_access();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment