メソッドとconstアクセス
Coddyの「Dart開発者のためのC++」コースのレッスン 34/48。
Dartにはメソッド用のconst修飾子はありません。final変数は変数の再代入を防ぐだけなので、b.rename(...)は引き続きオブジェクトを変更する可能性があり、Dartのconstは読み取り専用のビューではなく、コンパイル時定数の値を意味します。C++では、インスタンスメソッドは暗黙的にこれを受け取ります。constメンバー関数はconst参照を通じて呼び出せます。
Dart
class Badge {
String name;
Badge(this.name);
void rename(String n) => name = n;
String label() => name;
}
void main() {
final b = Badge('old');
b.rename('new');
print(b.label());
}
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";
}
各プログラムを個別にトレースしてください。これらの例は、課題とは異なる操作やデータを使って概念を示しています。ソースの出力とターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力:開始値と符号付きの変化量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";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Dart開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ