Header File Content Puzzle [Interview Question]

What should be the contents of the Fill.hpp header file so that the following code works, i.e. both assert work?

 #include <iostream> #include <string> #include <cassert> #include "Fill.hpp" int main() { std::string s = multiply(7,6); int i = multiply(7,6); assert(s == "42"); assert(i == 42); } 

TIA

+6
source share
4 answers

Define conversion functions for converting multiply to int and std::string , as shown in Method 1 or use Method 2 (similar to 1)

Method 1

 struct multiply { int t1,t2; operator std::string() { std::stringstream k; k<<(t1*t2); return k.str(); } operator int() { return t1*t2; } multiply(int x, int y):t1(x),t2(y){} }; 

Method 2

 class PS { int _value; public: PS(int value) : _value(value) {} operator std::string() { std::ostringstream oss; oss << _value; return oss.str(); } operator int() { return _value; } }; PS multiply(int a, int b) { return PS(a * b); } 
+15
source
 class Number { public: Number(int i) { value = i; } // So that integer can be converted to class instances. public: operator std::string() { return .... // Code to convert to string for first assignment to work. } operator int() { return value; // For second assignment to work. } public: int value; } Number multiply(Number a, Number b) { .... // code to multiply both numbers and return the result. } 
+2
source

The simplest answer I can think of:

 // Fill.hpp struct multiply { multiply(int, int) {} operator std::string() { return "42"; } operator int() { return 42; } }; 
+1
source

How about simple:

 #define NDEBUG 
0
source

Source: https://habr.com/ru/post/886626/


All Articles