当前位置:网站首页>Dynamic creation and release, assignment and replication of objects
Dynamic creation and release, assignment and replication of objects
2022-04-23 06:37:00 【*Flowers bloom on the street】
One 、 Dynamic creation and release of objects
utilize new Operators can dynamically Allocate object space ,delete Operator Freeing object space .
The general form of dynamically allocating objects :
new Class name ;
use new The object dynamically allocated by the operator is nameless , It returns the value of a pointer to a new object , That is, the starting address of the allocated memory unit . The program can access this object indirectly through this address , Therefore, you need to define a pointer variable to the object of the class to store the address .
Class name * Object pointer variable ;
Object pointer variable = new Class name ;
Such as : student *p; p = new student;
In execution new Operation time , If there is not enough memory , Unable to open up the required memory space ,C++ The compiler will return a 0 Value pointer (NULL). therefore , Just check whether the return value is 0, You can judge whether the dynamic allocation object is successful , Object pointers can only be used when the pointer is valid .
When no longer needed, use by new When creating dynamic objects , Must use delete The operation is cancelled .
Such as : delete p;
Be careful :new Dynamic objects created are not automatically undone , Even if the program ends , It has to be used artificially delete revoke .
#include<iostream>
using namespace std;
class Object
{
private:
int value;
public:
Object(int x = 0) :value(x) {}
void Print()const { cout << value << endl; }
};
void fun()
{
Object obja(20);//.stack
}
int main()
{
Object objb(40);
fun();
Object* p = new Object(30);//new 1. To apply for space 2. Create objects 3. Return the address of the created object .heap
p->Print();
delete p;// When you don't need to delete
}
Object *p = new Object[n];// When building multiple objects at once , There must be a default constructor , There is no default constructor , Cannot continuously build objects .( If the constructor No parameters , Or constructor All parameters have default values , You can call it the default constructor . In a class , There can only be one default constructor .)
Two 、 Object assignment and replication
1> Assignment of objects
If a class defines two or more objects , Then these objects of the same kind can assign values to each other .
The general form of object assignment :
Object name 1= Object name 2;
Description of object assignment :
1) Only the data of non static members is assigned , Instead of assigning values to member functions .
2) The data member of the object cannot include the data of dynamically allocating resources , Otherwise, serious consequences may occur during assignment .
2> Replication of objects
Sometimes you need to use multiple identical objects , You can quickly copy multiple identical objects with an existing object .
The general form of object replication :
Class name Object name 2 ( Object name 1);
student stu2 (stu1) ;
Call a special constructor when creating an object — copy constructor . If the user Undefined copy constructor , Then the compiling system will Automatically provide a default copy constructor .
Such as : student stu2 (stu1) ;
Corresponding copy constructor :
student::student(const student &stu)
{
num=stu.num;
name=stu.name;
score =stu.score;
}
#include<stdio.h>
#include<iostream>
using namespace std;
class student
{
private:
int num;
string name;
float score;
public:
student(int n, string m, float s) :num(n), name(m), score(s){};
student(const student& stu);
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "score:" << score << endl;
}
};
student::student(const student&stu)// copy constructor
{
num = stu.num;
name = stu.name;
score = stu.score;
}
int main()
{
student stu1(2020, "zhangsan", 85);
student stu2(stu1);// Copy
stu1.display();
stu2.display();
return 0;
}
C++ It also provides another user-friendly copy form —— Replace parentheses with assignment numbers .
The general form of object replication :
Class name Object name 2 = Object name 1;
The difference between the assignment of an object and the copy of an object :
1) The assignment of an object is to assign a value to an existing object , The assigned object must be defined first , Can be assigned .
2) If the copy of an object is to create a new object , And make it exactly the same as an existing object .
The difference between ordinary constructor and copy constructor :
1) The declaration is different in form .
Class name ( Parameter list )
Class name ( Class name & Object name )
Such as : student( int num, string name, int score);
student (student &stu);
2) When creating an object , Argument types are different .
Such as : student stu1( 20060102,“ Zhang San ”,86 );
student stu2( stu1);
3) Ordinary constructors are called when creating objects .
The copy constructor is called when copying a new object from an existing object .
版权声明
本文为[*Flowers bloom on the street]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230547207094.html
边栏推荐
- Export the articles written in CSDN to PDF format
- Guaba and Computational Geometry
- Arcpy为矢量数据添加字段与循环赋值
- Rust:如何 match 匹配 String 字符串?
- xlsxwriter.exceptions.FileCreateError: [Errno 13] Permission denied问题
- 定位器
- Database - sorting data
- 基于Sentinel+Nacos 对Feign Client 动态添加默认熔断规则
- 爬取手游网站游戏详情和评论(MQ+多线程)
- Robocode教程3——Robo机器剖析
猜你喜欢
Addition, deletion, modification and query of MySQL table
ArcGIS license错误-15解决方法
P1586 solution to tetragonal theorem
Robocode教程7——雷达锁定
Guaba and Computational Geometry
Integration and induction of knowledge points of automatic control principle (Han min version)
Explanation of the second I interval of 2020 Niuke summer multi school training camp
批量导出Arcgis属性表
-- SQL query and return limit rows
Solution to the trial of ycu Blue Bridge Cup programming competition in 2021
随机推荐
Import of data
Basemap库绘制地图
[leetcode 290] word rules
Detailed arrangement of knowledge points of University probability theory and mathematical statistics
jenkspy包安装
C array
Techniques et principes de détection
Arcpy为矢量数据添加字段与循环赋值
根据SQL语句查询出的结果集,将其封装为json
Rust 的多线程安全引用 Arc
pyppeteer爬虫
Rust:如何实现一个线程池?
Flask操作多个数据库
Rust的闭包类型(Fn, FnMut, FnOne的区别)
安装pyshp库
[leetcode 228] summary interval
Record the installation and configuration of gestermer on TX2, and then use GST RTSP server
Robocode教程4——Robocode的游戏物理
Programming training
LockSupport. Park and unpark, wait and notify