非是非
Thinking, Express
|

测验题目

问题:
    编译运行下图中的C++代码,结果是什么?
    
    #include <iostream>
    
    class A {
    
    private:
            int value;
    public:
    
      A(int n) { value = n; }
    
      A(A other) {
        value = other.value;
      }
    
      void print() {
        std::cout << value << std::endl;
      }
    };
    
     
    
    int main(int argc, char* argv[]) {
      A a = 10;
      A b = a;
    
      b.print();
    
      return 0;
    }
    
    
    编译运行正常,输出10
    编译错误
    编译成功,运行时程序崩溃
    参考答案:
    编译错误。在复制构造函数中传入的参数是A的一个实例。由于是传值,把形参拷贝到实参会调用复制构造函数。因此如果允许复制构造函数传值,那么会形成永无休止的递归并造成栈溢出。因此C++的标准不允许复制构造函数传值参数,而必须是传引用或者常量引用。在Visual
    Studio和GCC中,都将编译出错。
    非是非 | 联系 | 关于 | 向开发者捐赠 |

    版权所有 © 非是非, 2007~2015

    我觉得这个站点或页面: 有用 没用 有趣 无趣 有错 |