📜  C++程序的输出|套装14

📅  最后修改于: 2021-05-30 09:07:13             🧑  作者: Mango

预测以下C++程序的输出。

难度等级:新秀

问题1

#include 
using namespace std;
  
class A
{
    int id;
public:
    A (int i) { id = i; }
    void print () { cout << id << endl; }
};
  
int main()
{
    A a[2];
    a[0].print();
    a[1].print();
    return 0;
}

“ A a [2]”行中存在编译错误。类A中没有默认构造函数。当我们编写自己的参数化构造函数或复制构造函数时,编译器不会创建默认构造函数(请参阅此Gfact)。我们可以通过在类A中创建默认构造函数,或使用以下语法通过参数化构造函数初始化数组成员来修复错误。

// Initialize a[0] with value 10 and a[1] with 20 
 A a[2] = { A(10),  A(20) } 

问题2

#include 
using namespace std;
  
class A
{
    int id;
    static int count;
public:
    A()
    {
        count++;
        id = count;
        cout << "constructor called " << id << endl;
    }
    ~A()
    {
        cout << "destructor called " << id << endl;
    }
};
  
int A::count = 0;
  
int main()
{
    A a[2];
    return 0;
}

输出:

constructor called 1
constructor called 2
destructor called 2
destructor called 1

在上面的程序中,首先创建对象a [0],但是首先破坏对象a [1]。对象总是按照与创建相反的顺序销毁。顺序相反的原因是,稍后创建的对象可能会使用先前创建的对象。例如,考虑以下代码片段。

A a;
B b(a);

在上面的代码中,对象“ b”(在“ a”之后创建)可以在内部使用“ a”的某些成员。因此,在“ b”之前破坏“ a”可能会造成问题。因此,对象“ b”必须在“ a”之前销毁。

问题3

#include 
using namespace std;
  
class A
{
   int aid;
public:
   A(int x)
   { aid = x; }
   void print()
   { cout << "A::aid = " <

编译器错误:对B :: a的未定义引用
B类具有静态成员“ a”。由于成员“ a”是静态的,因此必须在类外部进行定义。 A类没有Default构造函数,因此我们还必须在定义中传递一个值。添加一行“ AB :: a(10);”将使程序正常工作。

以下程序运行正常,并将输出显示为“ A :: aid = 10”

#include 
using namespace std;
  
class A
{
   int aid;
public:
   A(int x)
   { aid = x; }
   void print()
   { cout << "A::aid = " <
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”