I have this 'Person' class:
class Person {
public:
Person(Age age) : m_age(age) {}
virtual ~Person() noexcept {}
virtual double ComputeEarnings() = 0;
static MaxInstances GetNumberOfInstances() {
return number_of_instances;
}
// Possible causes for the problem:
// 1. 'std::ostream' doesn't distinguish between 'unsigned char' and 'std::uint8_t'
// (which is still a 'char' type on many compilers). Explicit casting to 'int'
// forces 'ostream' to interpret it as a numeric value.
//
// 2. 'ostream' may still interpret 'std::uint8_t' as a character when streamed. This
// happens because 'ostream' prioritizes overloads for 'char' types over numeric ones.
//
// Possible solutions that don't work:
// 1. Double static casting to unsigned int and then int OR unsigned int and then unsigned int.
// 2. Unary '+'.
// 3. Set to a variable with implicit or explicit type cast (neither work).
friend std::ostream& operator<<(std::ostream& os, const Person& person) {
int numeric_age = static_cast<int>(person.m_age);
return os << numeric_age;
}
private:
// Shared across all instances of a class, but with private access (through the getter).
static MaxInstances number_of_instances;
protected:
Age m_age;
};
and I've tried everything, but it always prints the ASCII of the first character (e.g. age = 20 -> it will print 50). I tried it on another program:
#include <iostream>
#include <cstdint>
using Age = std::uint8_t;
class Person {
public:
explicit Person(Age age) : m_age(age) {}
friend std::ostream& operator<<(std::ostream& os, const Person& person) {
os << +person.m_age;
return os;
}
private:
Age m_age;
};
int main() {
Person p{23};
std::cout << "Age: " << p << std::endl; // Outputs: Age: 23
return 0;
}
and here it works just the way I want it to. Why does this happens? Any help is appreciated :)