注册 登录
编程论坛 C++教室

请教各位大虾,面向对象的题目,怎样不修改主函数和子函数的条件下修改输出内容??

babyly1314 发布于 2008-11-05 19:00, 848 次点击
有两个题目,小弟百思不得其解,请指教,我想第一个题目应该用继承性来做,第二个还没有头绪……请教
# include <stdio.h>
void  hello () { printf(“ Hello, world!\n”); }
int  main ()
{
 hello(); return 0;
}
试修改上面的程序,使其输出变成:
Begin
  Hello, world!
End

限制:(1)不能对main()进行任何修改;(2 )不能修改hello()中的printf语句,也不能在hello()中增加任何其他可执行语
       句。

2. 用C++语言定义MyType  (包括方法体),使之能够通过下面的测试程序:
    int main()
    {
      MyType<int>           s1(10), s2(-5), s3;
      MyType<double>        s4(10.3), s5(5.2), s6;
      s3 = s1 + s2;
      s6 = s4 - s5;
      printf(" s1.value = %d  s2.value = %d   s3.value = %d\n", s1.getValue(), s2.getValue(), s3.getValue());
      printf(" s4.value = %2.1f s5.value = %2.1f   s6.value = %2.1f\n",  s4.getValue(), s5.getValue(), s6.getValue());
      return 0;
    }

该测试程序的输出应为:
    s1.value = 10  s2.value = -5 s3.value = 5
    s4.value = 10.3  s5.value =  5.2 s6.value = 5.1
3 回复
#2
中学者2008-11-05 19:31
有意思~~~~
第一题:
#include <stdio.h>
namespace HELLO
{
void  hello () { printf(“ Hello, world!\n”); }
}
void hello()
{
    printf("Begin\n");
    HELLO::hello();
    printf("End\n");
}
int  main ()
{
hello(); return 0;
}
第二题:(只做到了符合你的要求...没做更多的要求~)
template<typename _Ty>
class MyType
{
public:
    MyType() {};
    MyType(_Ty const& val) { val_=val; }
    friend
    const MyType operator+ ( MyType<_Ty> const& lp,MyType<_Ty> const& rp)
    {
        return MyType(lp.val_,rp.val_);
    }
    friend
    const MyType operator- (MyType<_Ty> const&lp,MyType<_Ty> const& rp)
    {
        return MyType(lp.val_,-rp.val_);
    }
    _Ty getValue() const { return val_; }
private:
    MyType(_Ty const& lv,_Ty const&rv) { val_=lv+rv; }
private:
    _Ty val_;
};
int main()
    {
      MyType<int>           s1(10), s2(-5), s3;
      MyType<double>        s4(10.3), s5(5.2), s6;
      s3 = s1 + s2;
      s6 = s4 - s5;
      printf(" s1.value = %d  s2.value = %d   s3.value = %d\n", s1.getValue(), s2.getValue(), s3.getValue());
      printf(" s4.value = %2.1f s5.value = %2.1f   s6.value = %2.1f\n",  s4.getValue(), s5.getValue(), s6.getValue());
      return 0;
    }
#3
babyly13142008-11-05 19:53
非常感谢,但我还是看不太懂~谢谢了!
#4
newyj2008-11-05 20:49
第一题 不知道 是否符合lz的要求
程序代码:
#include<stdio.h>
#define hello() hello()()
class hello
{
   public:
     const hello& operator()(){printf("Begin\n  Hello,world!\nEnd\n");return *this;}      
};

//void  hello () { printf(“ Hello, world!\n”); }

int main()
{
hello();return 0;      
}

第二题 和版主的差不多 就不贴出来了
1