预测以下C ++程序的输出:
#include <iostream>
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;
}
输出:
B's Constructor Called
上面的程序仅调用B的构造函数,而不调用A的构造函数。原因很简单,静态成员仅在类声明中声明,而未定义。必须使用范围解析运算符在类外部明确定义它们。
如果我们尝试访问静态成员“ a”而不对其进行显式定义,则会收到编译错误。例如,以下程序编译失败。
#include <iostream>
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的构造函数。请参阅以下程序。
#include <iostream>
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'。
#include <iostream>
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语言C++编程学习交流圈子,**QQ群【951258402】**微信公众号:C语言编程学习基地
分享(源码、项目实战视频、项目笔记,基础入门教程)
欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!
编程学习视频分享: