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
619cf7f2
Commit
619cf7f2
authored
Nov 21, 2022
by
Administrator
Browse files
add static member and static function
parent
53c6f4ce
Changes
2
Hide whitespace changes
Inline
Side-by-side
02.OOP/StaticFunc.cpp
0 → 100644
View file @
619cf7f2
#include <iostream>
using
namespace
std
;
class
Box
{
public:
// 构造函数定义
Box
(
double
l
,
double
b
,
double
h
)
{
cout
<<
"Constructor called."
<<
endl
;
length
=
l
;
breadth
=
b
;
height
=
h
;
// 每次创建对象时增加 1
objectCount
++
;
}
double
Volume
()
{
return
length
*
breadth
*
height
;
}
// 静态成员函数即使在类对象不存在的情况下也能被调用
// 静态函数只要使用类名加范围解析运算符 :: 就可以访问。
// 静态成员函数只能访问静态数据成员,不能访问其他静态成员函数和类外部的其他函数。
// 静态成员函数有一个类范围,他们不能访问类的 this 指针。
// 可以使用静态成员函数来判断类的某些对象是否已被创建。
static
int
getCount
()
{
return
objectCount
;
}
private:
double
length
;
// 长度
double
breadth
;
// 宽度
double
height
;
// 高度
static
int
objectCount
;
};
// 初始化类 Box 的静态成员
int
Box
::
objectCount
=
0
;
int
main
(
void
)
{
Box
Box1
(
3.3
,
1.2
,
1.5
);
// 声明 box1
Box
Box2
(
8.5
,
6.0
,
2.0
);
// 声明 box2
// 输出对象的总数
cout
<<
"Total objects: "
<<
Box
::
getCount
()
<<
endl
;
return
0
;
}
\ No newline at end of file
02.OOP/StaticMember.cpp
0 → 100644
View file @
619cf7f2
#include <iostream>
using
namespace
std
;
class
Box
{
public:
// 成员为静态时,这意味着无论创建多少个类的对象,静态成员都只有一个副本
// 静态成员在类的所有对象中是共享的。
// 如果不存在其他的初始化语句,在创建第一个对象时,所有的静态数据都会被初始化为零。
// 不能把静态成员放置在类的定义中
// static int objectCount = 0;
static
int
objectCount
;
// 构造函数定义
Box
(
double
l
,
double
b
,
double
h
)
{
cout
<<
"Constructor called."
<<
endl
;
length
=
l
;
breadth
=
b
;
height
=
h
;
// 每次创建对象时增加 1
objectCount
++
;
}
double
Volume
()
{
return
length
*
breadth
*
height
;
}
private:
double
length
;
// 长度
double
breadth
;
// 宽度
double
height
;
// 高度
};
// 初始化类 Box 的静态成员
int
Box
::
objectCount
=
0
;
int
main
(
void
)
{
Box
Box1
(
3.3
,
1.2
,
1.5
);
// 声明 box1
Box
Box2
(
8.5
,
6.0
,
2.0
);
// 声明 box2
// 输出对象的总数
cout
<<
"Total objects: "
<<
Box
::
objectCount
<<
endl
;
return
0
;
}
\ 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