Menu
CoddyTech

メソッドとconstアクセス

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

C# の readonly struct メンバーは、通常のメンバー関数に対する C++ の const 修飾よりも役割が限定されています。C++ のインスタンスメソッドは、これを暗黙的に受け取ります。const メンバー関数は const 参照を通じて呼び出すことができます。

C#

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Badge {string name;public Badge(string n){name=n;}public void Rename(string n){name=n;}public string Label(){return name;}}
static void Main() {
var b=new Badge("old");b.Rename("new");Console.WriteLine(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";
}

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

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++オンラインコンパイラ