変更可能な構造体API
Coddyの「C++開発者のためのC」コースのレッスン 25/48。
C++の構造体には、メソッド、コンストラクター、アクセス制御、仮想動作を持たせることができます。Cの構造体にはデータフィールドが含まれます。通常の関数はレシーバーへのポインターを明示的に受け取り、状態の不変条件を自ら実装します。
状態を変更する関数は、構造体へのポインターを明示的に受け取ります。操作が拒否された場合に状態が維持されるよう、最初に検証します。Cには暗黙のレシーバーはありません。
C++の例
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
struct Account{int balance;void spend(int n){balance-=n;}};
int main(){
Account a{5};a.spend(2);std::cout<<a.balance<<"\n";
}
C++の出力:
3Cの例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Account {int balance;};
int main(void) {
struct Account a={5};struct Account *p=&a;p->balance-=2;printf("%d\n",a.balance);
return 0;
}
Cの出力:
3チャレンジ
簡単Account には整数の balance が格納されています。withdraw(account,amount) を実装してください。amount が負、または残高不足の場合は変更せずに false を返し、それ以外の場合は差し引いて true を返します。0 は有効です。入力は残高と amount、出力は success:balance です。ドライバーは、独立したアカウントと拒否時に状態が変化しないことも検証します。
ロックされていないソースファイルとヘッダーファイルを編集してください。可視のロックされた main.c から直接呼び出されるため、宣言済みの公開 API との互換性を保ってください。別の main を追加しないでください。タスクで範囲を明示的に確認する場合を除き、数値のテストデータはすべてオーバーフローを避けられる程度に小さい値です。指定された出力のみを表示してください。入力解析と出力を示す場合はドライバーが行います。
自分で試してみよう
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){Account a;int amount;if(scanf("%d%d",&a.balance,&amount)!=2)return 1;Account x={4},y={9};if(withdraw(&x,5)||x.balance!=4||withdraw(&x,-1)||x.balance!=4||!withdraw(&x,2)||x.balance!=2||y.balance!=9)return 2;int ok=withdraw(&a,amount);printf("%d:%d\n",ok,a.balance);return 0;}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのCのすべてのレッスン
自分で練習してみよう: Cオンラインコンパイラ