Menu
CoddyTech

メソッドとconstアクセス

Coddyの「C開発者のためのC++」コースのレッスン 34/48。

Cのミューテータは、オブジェクトへのポインタを明示的に受け取ります。C++のインスタンスメソッドは、暗黙のthisポインタを受け取り、メンバーに直接アクセスできます。読み取り専用のメンバー関数にはconstを付けると、呼び出し元はconst参照を通じてそれらを呼び出せます。constは、参照可能なすべての外部オブジェクトが不変であることを意味するわけではありません。

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct Badge {const char* name;};void rename_badge(struct Badge* b,const char* n){b->name=n;}
int main(void){
struct Badge b={"old"};rename_badge(&b,"new");puts(b.name);
return 0;
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge {std::string name;void rename(std::string n){name=std::move(n);}std::string label()const{return name;}};
int main(){
Badge b{"old"};b.rename("new");const Badge& r=b;std::cout<<r.label()<<"\n";
}

各プログラムを個別に追跡してください。これらの例は、課題とは異なる操作やデータを使って概念を示しています。ソースとターゲットの出力が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力:初期値と2つの符号付き変化量。Counter.addはインスタンスを変更します。valueはconstで、現在の状態を返します。

編集可能なモジュール:Counter.cpp、Counter.hpp。各必須型には、それぞれ名前付きのヘッダーと実装があります。すべての公開シグネチャを保持してください。ロックされたmain.cppは標準入力を読み取り、APIを直接呼び出します。また、記載されている場合は公開APIの動作も個別に確認します。API内で出力するのではなく、値を返してください。整数の入力値と結果は符号付きintの範囲内です。特に指定がない限り、テキストはASCIIです。

自分で試してみよう

#include "Counter.hpp"
#include <iostream>
int main(){
{Counter a(2),b(9);a.add(5);const Counter& r=a;if(r.value()!=7||b.value()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n,a,b;in>>n>>a>>b;Counter c(n);c.add(a);c.add(b);std::cout<<c.value()<<"\n";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ