开发者

Header File Content Puzzle [Interview Question]

What shou开发者_高级运维ld be the content of the header file Fill.hpp such that the following code works i.e both asserts 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


Define conversion functions for converting a type multiply into 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);
}


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.
}


The simplest answer I can think of:

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


How about the simple:

#define NDEBUG
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜