预测以下C++程序的输出:
C++
#include
using namespace std;
class A
{
public:
A() { cout << "A's Constructor Called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's Constructor Called " << endl; }
};
int main()
{
B b;
return 0;
}
C++
#include
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
int main()
{
B b;
A a = b.getA();
return 0;
}
C++
#include
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a = b1.getA();
return 0;
}
C++
#include
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
// static member 'a' is accessed without any object of B
A a = B::getA();
return 0;
}
输出:
B's Constructor Called
上面的程序仅调用B的构造函数,而不调用A的构造函数。原因很简单,静态成员仅在类声明中声明,而未定义。必须使用范围解析运算符在类外部明确定义它们。
如果我们尝试访问静态成员“ a”而不对其进行显式定义,则会收到编译错误。例如,以下程序编译失败。
C++
#include
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
int main()
{
B b;
A a = b.getA();
return 0;
}
输出:
Compiler Error: undefined reference to `B::a'
如果我们添加a的定义,则该程序将正常运行并将调用A的构造函数。请参阅以下程序。
C++
#include
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a = b1.getA();
return 0;
}
输出:
A's constructor called
B's constructor called
B's constructor called
B's constructor called
请注意,上面的程序对3个对象(b1,b2和b3)调用B的构造函数3次,但仅调用A的构造函数一次。原因是,静态成员在所有对象之间共享。这就是为什么它们也被称为班级成员或班级字段的原因。同样,可以在没有任何对象的情况下访问静态成员,请参见下面的程序,其中在没有任何对象的情况下访问静态成员’a’。
C++
#include
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
// static member 'a' is accessed without any object of B
A a = B::getA();
return 0;
}
输出:
A's constructor called
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。