C++学习笔记(六):类之间的关系

1.组合

一个类的成员变量,包含另一个类的对象。

例子:Line类中有Point类对象

#include<iostream>
using namespace std;
class Point{
public:
    Point(int xx=0, int yy=0);
    Point(const Point &p);
    ~Point(){
        cout<<x<<':'<<y<<"Object destroyed."<<endl;
    }
    void showPoint(){
        cout<<x<<':'<<y<<endl;
    }

private:
    int x, y;
};

Point::Point(int xx, int yy):
    x(xx),y(yy){
}

Point::Point(const Point &p){
    x=p.x;
    y=p.y;
    cout<<"Calling the Point copy constructor"<<endl;
}

class Line{
public:
    Line(Point xp1, Point xp2);
    Line(const Line &q);
    ~Line(){
        cout<<"Object destroyed."<<endl;
    }
    void showLine(){
        cout<<"start:";
        p1.showPoint();
        cout<<"end:";
        p2.showPoint();
    }
private:
    Point p1, p2;
};

Line::Line(Point xp1, Point xp2):
    p1(xp1),p2(xp2){
}

Line::Line(const Line &q):p1(q.p1),p2(q.p2){
    cout<<"Calling the line copy constructor"<<endl;
}

void func1(Point p){
    p.showPoint();
}

Point func2(){
    Point a(11,11);
    return a;
}

void lineFc1(Line l){
    l.showLine();
}

Line lineFc2(Line l){
    return Line(l);
}

int main(){
    Point p1;
    Point p2(p1); //第一次调用复制构造函数
    p2.showPoint();
    cout<<"------------"<<endl;
    func1(p2);
    cout<<"------------"<<endl;
    p2 = func2();
    p2.showPoint();
    cout<<"------------"<<endl;
    Line l(p1,p2);
    l.showLine();
    return 0;
}

结果:

Calling the Point copy constructor
0:0
------------
Calling the Point copy constructor
0:0
0:0Object destroyed.
------------
11:11Object destroyed.
11:11
------------
Calling the Point copy constructor
Calling the Point copy constructor
Calling the Point copy constructor
Calling the Point copy constructor
0:0Object destroyed.
11:11Object destroyed.
start:0:0
end:11:11
Object destroyed.
11:11Object destroyed.
0:0Object destroyed.
11:11Object destroyed.
0:0Object destroyed.

因为Line中有很多的Point,所以输出比较复杂,可以一一对应相应的调试信息,不详细解释。

2.前向引用

当一个类要使用类另一个未定义的类时,先进行前向引用。

前向引用声明不定义任何细节;

#include<iostream>
using namespace std;
class B; //前向引用声明
class A{
//B b;
public:
    void f(B b);
};

class B{
public:
    void g(A a);
};

int main(){
    return 0;
}

但是当需要创建类的对象,而不只是在形参里使用时,由于细节信息的丢失,不能为其创建对象。此时前向引用声明报错!

3.友元

关键字  friend

#include<iostream>
using namespace std;
class Point{
public:
    Point(int xx=0, int yy=0);
    Point(const Point &p);
    ~Point(){}
    void showPoint(){
        cout<<x<<':'<<y<<endl;
    }
    friend void test(Point &p);

private:
    int x, y;
};

Point::Point(int xx, int yy):
    x(xx),y(yy){
}

void test(Point &p){
    cout<<p.x<<endl;
}

int main(){
    Point p1(2,3);
   //cout<<p1.x;直接在对象中.访问private出错
    test(p1);
    return 0;
}

友元的作用是将friend关键字所在的类中的private和protected类授权给后面的函数或类,使之可以通过类外访问,即可以通过 . 来访问,而不是给的函数接口。

如:friend void test(Point &p);   这句在Point类中,所以是把Point中的private变量x  y权限给test函数,使test函数体内可以使用.操作

3.继承

。。。

猜你喜欢

转载自blog.csdn.net/Wzz_Liu/article/details/82220552