2026-11-15
row_label.cpp
#include <iostream>
#include <string>
std::string label(double ratio) {
return std::to_string(static_cast<int>(ratio * 100)) + "%";
}
std::string row(const std::string& name, int count) {
return name + ": " + label(count);
}
std::string label(int v) {
return std::to_string(v) + " items";
}
int main() {
std::cout << row("apples", 3) << '\n';
}
row は、品名と個数から 品名: 個数 items という1行を作るつもりの関数です。row("apples", 3) は apples: 3 items を返すはずが、いまは apples: 300% を返します。
Answer
Wrong
std::string label(double ratio) {
return std::to_string(static_cast<int>(ratio * 100)) + "%";
}
std::string row(const std::string& name, int count) {
return name + ": " + label(count);
}
関数の呼び出しで候補になるのは、呼び出しの位置より前に宣言された関数だけです。row の本体で label(count) をコンパイルする時点では、label(int) はまだ宣言されていません。候補は label(double) だけなので、int の 3 は 3.0 に変換されてそちらに渡ります。label(double) は割合を百分率で書く関数なので、3.0 * 100 から 300% を作ります。
ファイルの後ろで label(int) を定義しても、すでにコンパイルし終えた row の呼び出しは選び直されません。int から double への変換は暗黙に行われるので、コンパイルエラーにもなりません。
Right
std::string label(double ratio) {
return std::to_string(static_cast<int>(ratio * 100)) + "%";
}
std::string label(int v);
std::string row(const std::string& name, int count) {
return name + ": " + label(count);
}
row より前に label(int) の宣言を置きます。呼び出しの候補を決めるのに要るのは引数と戻り値の型だけで、本体の定義は後ろのままでかまいません。これで label(count) の候補は2つになり、変換の要らない label(int) が選ばれて apples: 3 items が返ります。label(int) の定義を row より前へ移しても同じように直ります。