头文件内容拼图[面试问题]

时间:2011-04-25 15:41:30

标签: c++ puzzle

头文件Fill.hpp的内容应该是什么,以便以下代码可以工作,即assert都可以工作?

#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

4 个答案:

答案 0 :(得分:15)

定义 conversion functions ,将类型multiply转换为intstd::string,如方法1 所示,或者使用方法2 (类似于1)

方法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){}
};

方法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);
}

答案 1 :(得分:2)

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 :(得分:1)

我能想到的最简单的答案:

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

答案 3 :(得分:0)

简单如何:

#define NDEBUG
相关问题