• 【C++学习教程04】const成员函数&构造函数&析构函数


    参考资料

    • 范磊C++(第6课)
    • VS2015

    const成员函数

    不改变成员对象的函数在函数体前加const

    #include"virtual.h"
    #include "stdafx.h"
    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    class A
    {
    public:
    	void func(int x, int y) const { i = x; j = y; }
    	void print() const{ cout << "两个数字相乘" << i*j << endl; }
    private:
    	int i;
    	int j;
    };
    int main(int argc, const char * argv[]) {
    
    	system("pause");
    	return 0;
    }
    

    报错:
    在这里插入图片描述

    构造函数

    构造函数的使用意义:
    在这里插入图片描述

    析构函数

    清除构造函数所占用的内存。
    在这里插入图片描述

    #include "stdafx.h"
    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    class rectangle
    {
    public:
    
    	rectangle() { cout << "构造函数在运行" << endl; }//默认构造函数:他的作用仅仅的创造这个对象,系统会默认创造,但是一旦写出系统就不再默认创造。
    	//rectangle() {}//可以创造多个构造函数。但是不能创建完全相同的构造函数。
    	rectangle(int l, int w) { length = l; width = w; }//构造函数,没有返回值。
    	~rectangle() { cout << "析构函数执行" << endl; }//析构函数,没有输入和返回值。一个类只能由一个析构函数
    	int area() { return length*width; }
    private:
    	int length;
    	int width;
    };
    int main(int argc, const char * argv[]) {
    	rectangle a(3,4);
    	cout<<"长方形a的面积:"<<a.area()<<endl;
    	rectangle b;
    	cout << "长方形b的面积:" << b.area() << endl;
    	system("pause");
    	return 0;
    }
    
  • 相关阅读:
    2021年2月13
    2021年2月12
    2021年2月11
    2021年2月10
    2021年2月9
    下载优化
    20180301越努力越轻松
    2018-03-01继续完善2
    2018-03-01继续完善
    2018-02-16 GetSameTypeQuestion
  • 原文地址:https://www.cnblogs.com/vrijheid/p/14222983.html
Copyright © 2020-2023  润新知