Cpp_友元

特点

  1. 不具有自反性
  2. 不具有传递性
  3. 不具有继承性

三种形式

  1. 外部函数友元
  2. 成员函数友元
  3. 类友元

外部函数友元

成员函数友元

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Object
{
private:
int value;
public:
Object(int x):value(x)
{

}
};
class Base
{
private:
int sum;
public:
Base(int x = 0):sum(x)
{

}
void fun(Object& obj)
{
obj.value = obj.value + sum;//error
}
};
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
class Object;//在Base前要声明
class Base
{
private:
int sum;
public:
Base(int x = 0):sum(x)
{

}
void fun(Object& obj);
};
class Object
{
private:
int value;
public:
Object(int x):value(x)
{

}
friend
};
void Base::fun(Object& obj)
{
obj.value = obj.value + sum;//error
}
int main()
{
Base base(10);
Object obja(20);
base.fun(obja);
return 0;
}

练习_Cpp_20220107

题目

  1. 总结const 与指针的关系

  2. 总结const 与引用的关系

  3. 总结this指针

  4. 设计矩形类

    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
    //left:指定矩形左上角的逻辑X坐标。
    //top:指定矩形左上角的逻辑Y坐标。
    //right:指定矩形右下角的逻辑X坐标。
    //bottom:指定矩形右下角的逻辑Y坐标。
    class Rectangle
    {
    private:
    int left, top, right, bottom;
    public:
    //实现默认构造函数和带参的构造函数
    //实现Set函数
    SetLeft;
    SetTop;
    SetRight;
    SetBottom;
    // 实现Get函数
    GetLeft;
    GetTop;
    GetRight;
    SetBottom;
    void Show() const
    {
    cout<<"left-top point is ("<<left<<","<<top<<:")"<<endl;
    cout<<"right-bottom point is ("<<right<<","<<bottom<<")"<<endl;
    }
    };
  5. 实现双向函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Object
    {
    private:
    int value;
    public:
    Object(int x = 0):value(x) {}
    ~Object() {}
    void SetValue(int x) {value = x;}
    int GetValue() {return value;}
    // 使用一个函数实现 SetValue 和 GetValue() 函数的功能
    };
  6. 实现Stack

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #define SEQ_INIT_SIZE 10
    #define SEQ_INC_SIZE 2
    class SeqStack
    {
    private:
    int *base;
    int *pos;
    int maxsize;
    public:
    SeqStack(int sz = SEQ_INIT_SIZE):maxsize(sz>SEQ_INIT_SIZE? sz:SEQ_INIT_SIZE)
    {
    base = pos = (int*)malloc(sizeof(int)*maxsize);
    if(NULL == base) exit(1);
    }
    //实现函数有:
    ~SeqStack; // 析构函数
    Get_Size; // 返回数据的个数
    Get_Capacity; // 返回容量
    Is_Empty; // 判空
    Is_Full; // 判满
    Push; // 入栈
    Pop; // 出栈
    Top; // 取栈顶数据 ,但不出栈
    };
  7. STL string - std::basic_string - cppreference.com

    1. 预习 STL中的string类型;
    2. 熟练掌握string类型中的方法。