C++学习 类定义(一)


前言

C++中,我们可以使用类定义自己的数据类型,用类来描述对象。

一、C++类的定义

C++中类的定义

calss 类的名称
{
public:
//构造函数、成员函数
private:
//数据成员
}

在类的定义中public是公共的,可以直接被外部访问或者调用,private是私有的,不能被外部访问调用。

#include<iostream>
#include<string>

using namespace std;

class Person
{
public:
Person(const string &nm):name(nm)  //初始化
{
}

string getName() const
{
return name;
}

private:
string name;
};

int main()
{
Person a("bill";
a.getName()return 0;
}

在类中的成员函数能够函数重载,可以使用别名来简化类,显示指定inline成员函数。

#include<iostream>
#include<string>

using namespace std;

class Screen
{
typedef string::size_type size; // 使用别名来简化类名称

public:
char get() const  
{
return contents[cursor];
}
char get(size r,size c) const  //这边对函数进行重载
{
size roe = r*width;
return contents[row+c];
}

private:
string contents;
size curdor;
size height,eidth;
}

int main()
{
Screen a;
a.get();
a.get(2,8);
return 0;
}

当函数写在class中,表示这个函数是一个内联函数,当然也可写在class外面,那就是外联函数,当函数写在class外面的时候可以通过inline将其 变为内联函数。
例如:

lass Screen
{
typedef string::size_type size; // 使用别名来简化类名称

public:
char get() const  
{
return contents[cursor];
}
char get(size r,size c) const  //这边对函数进行重载
{
size roe = r*width;
return contents[row+c];
}

private:
string contents;
size curdor;
size height,eidth;
}


//可以改成
class Screen
{
typedef string::size_type size; // 使用别名来简化类名称

public:
char get()  constchar get(size r,size c) constprivate:
string contents;
size curdor;
size height,eidth;
}

inline char Screen::getchar() const
{
return contents[cursor];
}
inline char Screen::getchar(size r,size c) const
{
size roe = r*width;
return contents[row+c];
}

如果类只有申明没有定义,那么就不能使用它的创建对象。
例如

class Screenint main()
{
Screen a;
return 0;
}
//这样是不行的

但是这个他是可以定义一个指针或者一个引用

class Screenint main()
{
Screen *a;//这个指针指向这个类型
Screen &b;
return 0;
}

在类定义中,可以使用另一个类的指针。例如:

class Screen;
class Person
{
public:

private:
Screen *ptr; //ptr指向Screen
Person *a; //指向它自己
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值