c++ 基本class语法 例子

1.类的接口

注意:

①默认参数在接口中被定义,在实现中被忽略。

②使用explicit意味着单参数构造函数不能用来创建隐式临时对象,这样在定义类的对象或赋值时,编译器能正确分析出类型不匹配的问题。

#ifndef IntCell_H
#define IntCell_H
/*
	仿真int型存储单元的类
*/
class IntCell
{
public:
	explicit IntCell(int initialValue = 0);
	int read() const;
	void write(int x);

private:
	int storeValue;
};

#endif

2.类的定义

注意:

①成员函数需声明为类的一部分,否则将被认为是全局的。

#include"IntCell.h"//在当前目录搜索,再去默认搜索目录搜索

IntCell::IntCell(int initialValue):storeValue(initialValue){}
//默认的初始值在接口.h中定义,在实现时被忽略

int IntCell::read() const 
{
	return storeValue;
}

void IntCell::write(int x) 
{
	storeValue = x;
}

3.使用定义的类

#include<iostream>
#include"IntCell.h"
using namespace std;

void main() 
{
	IntCell a;
	IntCell b(2);
	cout << "a=" << a.read() << endl;//输出字符串用双引号
	cout << "b=" << b.read() << endl;
	a.write(3);
	cout << "after input 3, a = " << a.read() << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值