×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / 这是一家公司C++面试题,以下代码有什么错误?
    class A {

    public:
    A() { m_a = 0x55;}
    ~A();

    BYTE m_a;
    };

    class B{

    public:
    B(A *pa) {m_b = pa->m_a};
    ~B();

    BYTE m_b;
    };

    class C{

    public:
    C();
    ~C();

    A M_A;
    B M_B;
    };

    C::C():M_B(&M_A)
    {
    B b = M_B;
    }
    • C::C():M_B(&M_A) ^^^^^^^^^^^^^^^^^^^^ M_B成员初始化好像有点问题。这成了M_B=&M_A, 编译就过不去
    • 问题好像出在:B b = M_B; 我认为 b的初始化不对。根据类B的构造函数,他应该有参数的。
    • C::C():M_B(&M_A) 的构造函数有问题。 M_A尚未初始化。
    • B(A *pa) {m_b = pa->m_a}; 中的;应该搁在}前,但我想这可能是你的笔误,其他没有错误。
      B(A *pa) {m_b = pa->m_a}; 中的;应该搁在}前,但我想这可能是你的笔误,其他没有错误。
      C::C():M_B(&M_A)中M_A的空间已经存在,只是还没有初始化,但可以使用。
      M_B(&M_A)调用了B的构造函数B(A* pa);
      B b=M_B,调用了缺省的构造函数B(B&)。
      • attention: in C::C():M_B(&M_A), &M_A is not the pass value of M_B's constructor, but the initialization of the member M_B in C class. Therefore, this is a problem.
        • 你有两点问题:
          1、在构造函数后用 : 紧接的是对成员变量的初始化,任何变量类型(类也是一种变量类型)都存在初始化函数,也就是说,对于普通变量,初始化函数是缺省的,例如你可以这样定义变量:int n(10),表示定义变量n并初始化为10,这实际上和你常见的类的构造函数是同一种表现形式,如 B b(a);在上面讨论的例子中如果B的构造函数不是B(A* pa),而是B(int a, int b),则可以有这种形式C::C():M_B(10, 12);

          2、如果存在M_B=&M_A; 这样的语句,也是正确的,如果类B有构造函数 B(A* pa),且有A M_A; 的定义,则M_B=&M_A调用了构造函数B(A* pa);
          • 补充一点,对成员变量的初始化也就是调用相应的初始化函数,对于类,也就是构造函数。
            • donot add more. PLease have a test!
              • 你试过吗?我在NT下用VC++,在Linux下用g++试了,没问题。
                • u r so stupid! Successful compilition doesnot mean the code is OK. Do you try all the condition? so u have to explain the code form theroy
                  • 你很有意思,如果我错了,你指出来就是了,大家网上讨论问题,都是为了互相学习,讨论清楚了对大家都是进步,你何必口出恶言,你在现实生活中也是这样无礼吗?作为一个IT从业人员,你有最基本的合作精神吗?
        • Agree!
    • Absolutely correct.
      • tak a rest! stand aside
        • if you declear like this : B M_B; A M_A; in class C defination, then this is wrong!
    • The only error here is the destructor should be defined as: ~A(){} , ~B(){}. Don't just declare them as : ~A();~B();
      • 呵呵,那你还得加上C::~C(){} , typedef unsigned char BYTE;
        • You don't need because it already have: C::C():M_B(&M_A) { B b = M_B; } , this is absolutely definition. As to the BYTE, it depends on the compiler.
          • you are right. it seemed that someone should go to learn more about c++.
    • 看看下面的有什么错?
      class A
      {
      public:
      A()
      {
      m_a = 0x55;
      try
      {
      throw new int;
      }
      catch(...)
      {
      cout<<"error";
      }
      }
      int m_a;
      };

      class B
      {
      public:
      B(A *pa) {m_b = pa->m_a;}
      int m_b;
      };

      class C
      {
      public:
      C();

      B M_B;
      A M_A;
      };

      C::C():M_B(&M_A)
      {
      B b = M_B;
      }
      • 错误!正如我以前的贴子,M_A的说明必须放在M_B之前。另外,有内存泄漏。
    • B b = M_B; class B没有定义此operator.