类的几大函数
来源:互联网 发布:漫画控无网络连接 编辑:程序博客网 时间:2024/06/06 01:54
在类中由几个特殊而重要的函数:constructor,copy constructor,destructor,assignment operator(=).说它们特殊是因为它们负责类对象的创建,复制,赋值和销毁.如果用户自己没有在类中定义这几个函数,那么编译器会自动生成它们的默认版本(default version).一下内容转载自这里.
Constructor
usage:
features:
- constructor has same name as the class itself
- constructor don't have return type
- if we don't specify a constructor,c++ compiler generates adefault constructor for us
default constructor
In C++, the standard describes the defaultconstructor for a class as a constructor that can be called with no arguments(this includes a constructor whose parameters all have default arguments)
Remember that each class can have at mostone default constructor, either one without parameters, or one whose allparameters have default values.
Compiler doesn’t create a defaultconstructor if we write any constructor even if it is copy constructor. Butreverse is not true. Compiler creates a copy constructor if we don’t write ourown.
- without any arguments or with default value for every argument.
- if we define our own constructor, compiler doesn’t create the default constructor.
- If a class has no explicitly defined constructors, the compiler will implicitly declare and define a default constructor for it. This implicitly defined default constructor is equivalent to an explicitly defined one with an empty body.
- If constructors are explicitly defined for a class,but they are all non-default, the compiler will not implicitly define a defaultconstructor, leading to a situation where the class does not have a defaultconstructor. This is the reason for a typical error,
Copy Constructor
a member function which initializesan object using another object of the same class,Compiler also creates a copyconstructor if we don’t write our own copy constructor.Unlike defaultconstructor, body of compiler created copy constructor is not empty, it copiesall data members of passed object to the object which is being created(this isshallow copy).
function prototype:
ClassName (const ClassName &old_object)
when is copy constructor called?
- when an object of the class is returned by value
- when an object of the class is passed(to a function)by value as an argument
- when an object is constructed based on another object of the same class
- when compiler generates a temporary object
when is user defined copy constructor needed?
runtime allocation of resource like new, file handle,a network connection...etc
default copy constructor does only shllow copy
deep copy is possible only with user defined copy constructor
copy constructor vs assignment operator
- copy constructor is called when a new boject is created from an existing object,as a copy of the existing object.
- assignment operator is called when an already initialized object is assigned a new value from another existing object.
myclass t1,t2; myclass t3 = t1;//copy constructor myclass t4(t1);//copy constructor t2 = t1;//assignment operator
can we make copy constructor private?
yes,if so,objects of that class would become non-copyable.why argument to a copy constructor must be passed as a reference?
A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be pass by value.why argument to a copy constructor should be const?
Destructor
When is destructor called?
A destructor function is called automatically when the object goes out of scope:- the function ends
- the program ends
- a block containing local variables ends
- a delete operator is called
When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fineunless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.Can a destructor be virtual?
Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function.Can a destructor be private?
Yes,wheneverwe want to control destruction of objects of a class, we make the destructorprivate. This situation is ok only for dynamically created objects, it mayhappen that you pass a pointer to the object to a function and the functiondeletes the object. If the object is referred after the function call, thereference will become dangling.
#include <iostream>class Test{private: ~Teset(){} friend void destructor(Test*);};void destructor(Test*ptr){ delete ptr; }int main(int argc, char *argv[]){ //proper use Test *ptr = new Test; destructor(ptr); //1 compiler error:local variable ‘test’ cannot be destructed because the destructor is private. // Test test; //2 copiler error // Test *t = new Test;//ok,because untill now,hasn't call destuctor // delete t; //error:destructor is called return 0;}
Playing with destructor
预测下面程序的输出
#include <iostream>using namespace std;int i;class A{public: ~A() { i=10; }};int foo(){ i=3; A ob; return i;}//此处调用ob的析构函数int main(){ cout << "i = " << foo() << endl; return 0;}
输出结果是:i = 3
为什么是3而不是10呢?
在函数foo()中,ob的析构函数会在它的生命周期结束时调用,即在foo()函数结束处调用,所以在ob调用析构函数改变i之前,i的值作为3返回了.
如何才能让返回值是10呢?
修改foo()函数:
int foo(){ i = 3; { A ob; } return i;}
总结:
- default copy constructor, default assignment operator, and default destructor are ok if a class has no pointer or any other runtime resources, because shallow copy is probably sufficient.or,if your class has pointers or other dynamic allocate resources,you need define copy constructor yourself,thus it is almost certain that you will need a destructor and override the assignment operator.
- 类的几大函数
- 【C++】几大函数总结
- 几类函数的求导
- Ant的几大实践
- .NET的几大热点
- .NET的几大热点
- 数据库的几大范式
- 农村户口的几大好处
- 人生的几大规则
- 减肥的几大误区
- 枚举的几大用法
- java的几大排序
- quartz的几大组建
- 送礼的几大原则
- 线程的几大状态
- SpringMVC的几大优势
- 几大坐标系的转换
- 几大排序的总结
- : Association references unmapped class
- Linux安装配置jdk与项目更换jdk
- select和epoll 原理概述&优缺点比较
- C++中引用(&)的用法和应用实例
- cuda7.5 和cuda8共存
- 类的几大函数
- C# + 图灵机器人
- kindeditor 自定义图标方法
- Python进程间通信之命名管道
- jsp九大内置对象
- 搜狐2017秋招研发工程师笔试题目
- Python中的多进程学习
- SpringMVC中静态资源访问
- hdu 1540 Tunnel Warfare 线段树 / set