C++ 12 类

类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once

#include <string>

using namespace std;

class Screen {
// 设置位友元
friend class Window_Mgr;

public:
// 默认构造函数
Screen() : contents("hello class"), cursor(0), width(5) {}
// 构造函数,默认实参 只能放在后面
// explicit 抑制构造函数定义的隐式转换
explicit Screen(string text, int cur = 0, int w = 5) : contents(text), cursor(cur), width(w) {}

typedef std::string::size_type index;
char get() const { return contents[cursor]; }
// 重载成员函数
inline char get(index x, index y) const;
// 显示指定内联函数
index get_cursor() const;

Screen& move(index row, index offset); // 将光标移动到某行某位

Screen& set(char); // 对光标指向位置赋值

Screen& display(std::ostream &os) { do_display(os); return *this; }
// 基于const的重载
const Screen& display(std::ostream &os) const { do_display(os); return *this; }

private:
string contents;
index cursor;
index width;
void do_display(std::ostream &os)const
{
os << contents << endl;
}
};

inline char Screen::get(index x, index y) const
{
index row = x * width;
return contents[row + y];
}

inline Screen::index Screen::get_cursor() const
{
return cursor;
}

类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "Screen.h"

Screen & Screen::move(index row, index offset)
{
index skip = row * width;
cursor = skip + offset;
// this 指针的使用
return *this;
}

Screen & Screen::set(char c)
{
contents[cursor] = c;
return *this;
}

类使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <sstream>
#include "Screen.h"
#include "Account.h"

using namespace std;

void display(Screen screen);

int main()
{
Screen screen;
cout << "get() = " << screen.get() << endl;
cout << "get(row,offset) = " << screen.get(0, 1) << endl;
screen.move(0, 4).set('a');
cout << "get() = " << screen.get() << endl;

Screen myscreen("hello xiaohui");
myscreen.set('*').display(std::cout);

const Screen const_screen;
const_screen.display(std::cout);

string content = "good morning";
// display(content); // 隐式转换为 Screen对象 explicit 抑制构造函数定义的隐式转换
display(Screen(content)); // 显式转换

Account ac1;
double rate = ac1.rate();
rate = Account::rate();

return 0;
}

void display(Screen screen)
{
screen.display(cout);
}

友元

1
2
3
4
5
6
7
8
9
10
#pragma once
#include "Screen.h";
class Window_Mgr {
public:
Window_Mgr& relocate(Screen::index wid, Screen& s) {
// Window_Mgr 为 Screen友元 ,可访问私有变量
s.width += wid;
return *this;
}
};

静态变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#pragma once
#include <string>
using namespace std;
class Account {
public:
// 类成员直接使用静态变量
void applyint() { amount += amount * interestRate; }
// 静态函数没有this指针,不能引用成员变量
static double rate() { return interestRate; }
static void rate(double);
private:
std::string owner;
double amount;
static double interestRate; // 静态变量 Account类型全体对象共享
static double initRate();
};

推荐文章