共有staticメンバー
Coddyの「Go開発者のためのC++」コースのレッスン 35/48。
Goでは、パッケージ関数と変数によって、静的なクラスメンバーを使わずに共有の動作を提供します。C++では、そのようなメンバーを型に結び付けます。C++の静的メンバーはインスタンスではなくクラスに属します。静的関数にはthisポインターがありません。
Go
package main
import (
"fmt"
)
func ticketLabel() string { return "ticket" }
func main() {
fmt.Println(ticketLabel())
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Scale {static int double_value(int n){return 2*n;}};
int main(){
std::cout<<Scale::double_value(6)<<"\n";
}
各プログラムを個別に追跡しましょう。これらの例は、課題とは異なる操作やデータを使って概念を示しています。ソースとターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力:非負のオブジェクト数。Ticket は共有の next_ から 1 で始まる連続した ID を割り当てます。reset は next_ を 1 にリセットします。ドライバーは n 個のチケットを作成し、それらの ID の合計を返します。
編集可能なモジュール:Ticket.cpp、Ticket.hpp。各必須型には、それぞれ名前付きのヘッダーと実装があります。すべての公開シグネチャを保持してください。ロックされた main.cpp は stdin を読み取り、API を直接呼び出します。また、指定されている場合は公開 API の動作も個別に確認します。API 内では出力せず、戻り値を返してください。整数の入力値と結果は符号付き int の範囲内に収まり、特に指定がない限りテキストは ASCII です。
自分で試してみよう
#include "Ticket.hpp"
#include <iostream>
int main(){
{Ticket::reset();Ticket a,b;if(a.id()!=1||b.id()!=2)return 21;Ticket::reset();Ticket c;if(c.id()!=1||a.id()!=1)return 22;}
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;in>>n;Ticket::reset();int sum=0;for(int i=0;i<n;++i){Ticket t;sum+=t.id();}std::cout<<sum<<"\n";
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Go開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ