静态对象是否调用构造函数?
2015-05-31 20:26
483 查看
#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是个空类,没有数据成员x,则就算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; } }; 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
上面的程序调用B的构造函数3次,但是只调用A的构造函数一次,因为静态成员变量被所有对象共享,这也是它被称为类变量的原因。同时,静态成员变量也可以通过类名直接访问,比如下面的程序没有通过任何类对象访问,只是通过类访问a。
int main() { // static member 'a' is accessed without any object of B A a = B::getA(); return 0; }
输出:
A's constructor called
【出处】http://www.cnblogs.com/lanxuezaipiao/p/4148155.html
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 一个简单的asp数据库操作类
- C#实现用于操作wav声音文件的类实例
- 在线管理数据库 类
- Lua面向对象之类和继承浅析
- Lua中类的实现原理探讨(Lua中实现类的方法)
- Lua教程(一):在C++中嵌入Lua脚本
- Lua中的类编程代码实例
- Lua教程(二):C++和Lua相互传递数据示例
- C#常用目录文件操作类实例
- c# 类和成员的修饰详细介绍
- C#类的创建与初始化实例解析
- 深入c# 类和结构的区别总结详解
- c#结构和类的相关介绍
- C#中类与结构的区别实例分析
- C#实现读写ini文件类实例
- C++联合体转换成C#结构的实现方法