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
9c7b2902
Commit
9c7b2902
authored
Nov 20, 2022
by
Administrator
Browse files
Basic grammer of class and object
parent
b4797ad0
Changes
1
Hide whitespace changes
Inline
Side-by-side
02.OOP/Class.cpp
0 → 100644
View file @
9c7b2902
#include <iostream>
#include <Windows.h>
using
namespace
std
;
class
Box
{
// 类成员可以被定义为 public、private 或 protected。默认情况下是定义为 private。
// public: 公有成员在程序中类的外部是可访问的。您可以不使用任何成员函数来设置和获取公有变量的值
// private: 私有成员变量或函数在类的外部是不可访问的,甚至是不可查看的。只有类和友元函数可以访问私有成员。
// protected: 保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的
// 实际操作中,我们一般会在私有区域定义数据,在公有区域定义相关的函数,以便在类的外部也可以调用这些函数
// private: 私有成员变量或函数在类的外部是不可访问的,甚至是不可查看的。只有类和友元函数可以访问私有成员。
private:
double
length
;
// Length of a box
double
breadth
;
// Breadth of a box
double
height
;
// Height of a box
// 构造函数,它会在每次创建类的新对象时执行。
// 构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。
// 构造函数可用于为某些成员变量设置初始值。
// protected: 保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的
protected:
double
volumn
;
// 体积
// protected: 保护成员变量或函数与私有成员十分相似,但有一点不同,保护成员在派生类(即子类)中是可访问的
public:
// 构造函数,它会在每次创建类的新对象时执行。
// 构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。
// 构造函数可用于为某些成员变量设置初始值。
Box
()
{
cout
<<
"Box构造函数执行"
<<
endl
;
};
// 析构函数,在每次删除所创建的对象时执行。
~
Box
()
{
cout
<<
"Box析构函数执行"
<<
endl
;
};
// 类成员函数,计算体积
double
getVolume
()
{
this
->
volumn
=
length
*
breadth
*
height
;
return
this
->
volumn
;
};
void
setLength
(
double
length
)
{
this
->
length
=
length
;
};
void
setBreadth
(
double
breadth
)
{
this
->
breadth
=
breadth
;
};
void
setHeight
(
double
height
)
{
this
->
height
=
height
;
};
};
int
main
()
{
// 解决控制台中文输出乱码
SetConsoleOutputCP
(
CP_UTF8
);
Box
Box1
;
// 声明 Box1,类型为 Box
Box
Box2
;
// 声明 Box2,类型为 Box
double
volume
=
0.0
;
// 用于存储体积
// box 1 详述
Box1
.
setHeight
(
5.0
);
Box1
.
setLength
(
6.0
);
Box1
.
setBreadth
(
7.0
);
// box 2 详述
Box2
.
setHeight
(
10.0
);
Box2
.
setLength
(
12.0
);
Box2
.
setBreadth
(
13.0
);
// box 1 的体积
volume
=
Box1
.
getVolume
();
cout
<<
"Box1 的体积:"
<<
volume
<<
endl
;
// box 2 的体积
volume
=
Box2
.
getVolume
();
cout
<<
"Box2 的体积:"
<<
volume
<<
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