2021年3月1日面向对象初讲

本文介绍了C++中的代码规范,包括命名空间、输入输出流等基本概念,并通过实例详细讲解了类的定义、构造函数的使用及new操作符的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码规范

using namespace std;//表示名字空间,表示使用名字的空间,std标准空间,就是一个范围

输入输出流

int a;
double b;
cin >> a >> b;
cout << a << " " << b << endl;

一些头文件

#include<string>//可以直接实现string的链接,输入输出


#include<iostream>
#include<string>
using namespace std;

int main(){
	string s1 = "jslkdjfl";
	string s2;
	cin >> s2;
	string s4 = s1 + s2;
	cout << s4;
	return 0;
}

#include<iostream>
using namespace std;

class CMyTime{
	private:
		int h;
		int m=20;
		int s;
	public:
		void setTime(int a,int b,int c){
			this->h = a;//cpp的this是一个指针,需要用它指向其成员
			this->m = b;
			this->s = c;
		}
		void showTime(){
			cout << this->h << ":" << this->m << ":" <<this->s<<endl;
		}
};

注意cpp的private和public不是单独写的。

#include <iostream>
#include"CMyTime.cpp"//同一个工程下调用使用双引号

int main(int argc, char** argv) {
	CMyTime t1;
	t1.setTime(7,40,30);
	t1.showTime();
	return 0;
}

构造函数

构造函数名和类名一致,和java类似,没有返回值,在创建类的时候添加参数,自动执行构造函数

构造函数一定要放在public中

构造函数默认为空,当添加了不同的构造参数后,程序会根据初始化时存入的参数不同自动进行调用相应的构造函数(重载)

当添加了带参数的构造函数后,原无参构造函数被覆盖,如果使用无参初始化,需要另外写一个无参构造函数

#include<iostream>
using namespace std;

class CMyTime{
		
	
	private:
		int h;
		int m=20;
		int s;
	public:
		CMyTime(int a,int b,int c){//三个参数的构造函数
		h = a;
		m = b;
		s = c ;
		}
		CMyTime(){//无参构造函数
		}
    	CMyTime(int a,int b){//两个参数的构造函数
            h = a;
            m = b;
            s = 0;
        }
		void setTime(int a,int b,int c){
			this->h = a;
			this->m = b;
			this->s = c;
		}
		void showTime(){
			cout << this->h << ":" << this->m << ":" <<this->s<<endl;
		}
	
};

new的使用

new创建了新的空间并且返回一个指向此空间的指针

int *a = new int(6);//new一个int型,值为6,并把它的指针赋值给a
int *a = new int[6];//开辟6大小的空间,注意中括号和小括号不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值