C++类以及构造函数实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88619134

一 第一个类的例子

1 代码

#include <iostream>
using namespace std;
class CRectangle {
    int x, y;
public:
    void set_values(int, int);
    int area(void) {return (x*y);}
};
    
void CRectangle::set_values(int a, int b) {
    x = a;
    y = b;
}
    
int main() {
    CRectangle rect;
    rect.set_values(3, 4);
    cout << "area: " << rect.area() << endl;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
area: 12

二 构造函数的例子

1 代码

#include <iostream>
using namespace std;
class CRectangle {
    int width, height;
public:
    CRectangle(int, int);
    int area(void) {return (width*height);}
};
    
CRectangle::CRectangle(int a, int b) {
    width = a;
    height = b;
}
    
int main() {
    CRectangle rect(3, 4);
    CRectangle rectb(5, 6);
    cout << "rect area: " << rect.area() << endl;
    cout << "rectb area: " << rectb.area() << endl;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
rect area: 12
rectb area: 30

三 构造函数和析构函数

1 代码

#include <iostream>
using namespace std;
class CRectangle {
    int *width, *height;
public:
    CRectangle(int, int);
    ~CRectangle();
    int area(void) {return (*width * *height);}
};
    
CRectangle::CRectangle(int a, int b) {
    width = new int;
    height = new int;
    *width = a;
    *height = b;
}
    
CRectangle::~CRectangle() {
    delete width;
    delete height;
}
    
int main() {
    CRectangle rect(3, 4), rectb(5, 6);
    cout << "rect area: " << rect.area() << endl;
    cout << "rectb area: " << rectb.area() << endl;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
rect area: 12
rectb area: 30

3 说明

析构函数特别适用于当一个对象被动态分配内存空间,而在对象被销毁时,我们希望释放它所占用的空间的时候。

四 重载类的构造函数

1 代码

#include <iostream>
using namespace std;
class CRectangle {
    int width, height;
public:
    CRectangle();
    CRectangle(int, int);
    int area(void) {return (width*height);}
}
;
    
CRectangle::CRectangle() {
    width = 5;
    height = 5;
}
    
CRectangle::CRectangle(int a, int b) {
    width = a;
    height = b;
}
    
int main() {
    CRectangle rect(3, 4);
    CRectangle rectb;
    cout << "rect area: " << rect.area() << endl;
    cout << "rectb area: " << rectb.area() << endl;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
rect area: 12
rectb area: 25

3 说明

当我们定义一个class而没有明确定义构造函数的时候,编译器会自动假设两个重载的构造函数(默认构造函数和复制构造函数)。

这两个默认的构造函数只有在没有定义其他的构造函数被明确定义的情况下才存在。如果任何其他有任意参数的构造函数被定义了,这两个构造函数就都不存在了。在这种情况下,如果要有默认构造函数和拷贝构造函数,就必须自已定义它们。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/88619134
今日推荐