Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
9c483d7e
Commit
9c483d7e
authored
Nov 21, 2022
by
Clark Lin
Browse files
Added copy construction function
parent
9c7b2902
Changes
1
Hide whitespace changes
Inline
Side-by-side
02.OOP/CopyConstruFunc.cpp
0 → 100644
View file @
9c483d7e
#include <iostream>
using
namespace
std
;
class
Box
{
private:
double
price
;
public:
Box
(
double
price
)
{
this
->
price
=
price
;
}
void
show
()
{
cout
<<
"Price is "
<<
this
->
price
<<
endl
;
}
};
int
main
()
{
// 对于普通类型的对象来说,它们之间的复制是很简单的,例如:
// int a = 100;
// int b = a;
// 而类对象与普通对象不同,类对象内部结构一般较为复杂,存在各种成员变量。
Box
a
(
100
);
Box
b
=
a
;
// 注意这里的对象初始化要调用拷贝构造函数,而非赋值
a
.
show
();
b
.
show
();
/*
* 从以上代码的运行结果可以看出,系统为对象 B 分配了内存并完成了与对象 A 的复制过程。
* 就类对象而言,相同类型的类对象是通过拷贝构造函数来完成整个复制过程的。
* 拷贝构造函数是一种特殊的构造函数,它在创建对象时,
* 是使用同一类中之前创建的对象来初始化新创建的对象。拷贝构造函数通常用于:
* 通过使用另一个同类型的对象来初始化新创建的对象。
* 复制对象把它作为参数传递给函数。
* 复制对象,并从函数返回这个对象。
*/
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment