C++:类操作

构造函数:    在创建一个新的对象时调用
析构函数:    在删除所创建的对象时调用
拷贝构造函数:在创建对象时,使用同一类中之前创建的对象来初始化新创建的对象
友元函数:    可以访问类的 private 和 protected 成员
内联函数:    在调用函数的地方扩展函数体中的代码
this指针:     指向对象本身
指向类的指针:如同指向结构的指针

用法示例代码:

#include <iostream>

using namespace std;

class Box
{
    public:
        Box(int  w, int h);
        Box(const Box &obj);
        ~Box(void);
        void setValue(int w, int h);
        int getVol(void);
        friend int show(const Box &box);
        int compare(Box box);

    private:
        int width;
        int height;
};

Box::Box(int w, int h)      // 带参数的构造函数
{
    width = w;
    height = h;

    cout << "构造函数" << endl;
}


//Box::Box(int w, int h):width(w),height(h)      // 用法同上
//{
//  cout << "构造函数" << endl;
//}

Box::Box(const Box &obj)    // 拷贝构造函数
{
    width = obj.width;
    height = obj.height;

    cout << "拷贝构造函数" << endl;
}

Box::~Box(void)           // 析构函数
{
    cout << "析构函数" << endl;
}

void Box::setValue(int w, int h)
{
    width = w;
    height = h;
}

int Box::getVol(void)
{
    return width*height;
}

int Box::compare(Box box)   // this指针
{
    return (this->getVol() > box.getVol());
}

int show(const Box &box)   // 友元函数
{
    cout << "友元函数,vol: " << box.height*box.width << endl;
}

int main(void)
{
    Box box(2, 5);
    Box *box1;    // 指向类的指针

    cout << "普通,Vol: " << box.getVol() << endl;
    cout << endl;

    box.setValue(6, 10);
    cout << "普通设置,Vol:" << box.getVol() << endl;
    cout << endl;

    box1 = &box;
    cout << "指针类,Vol: " << box1->getVol() << endl;
    cout << endl;

    Box BBox(box);
    cout << "拷贝构造,Vol: " <<  BBox.getVol() << endl;
    cout << endl;

    show(box);
    cout << endl;

    if(box.compare(BBox))
        cout << "This比较: box.getVol() > BBox.getVol()" << endl;
    else
        cout << "This比较: box.getVol() < BBox.getVol()" << endl;

    cout << endl;

    show(box);

    cout << endl;

    return 0;
}
[john@bogon C++]$ g++ class.cc      
[john@bogon C++]$ ./a.out 
构造函数
普通,Vol: 10

普通设置,Vol:60

指针类,Vol: 60

拷贝构造函数
拷贝构造,Vol: 60

友元函数,vol: 60

拷贝构造函数
析构函数
This比较: box.getVol() < BBox.getVol()

友元函数,vol: 60

析构函数
析构函数

猜你喜欢

转载自blog.csdn.net/keyue123/article/details/79175168