前言
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() const;
char get(size r,size c) const;
private:
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 Screen;
int main()
{
Screen a;
return 0;
}
//这样是不行的
但是这个他是可以定义一个指针或者一个引用
class Screen;
int main()
{
Screen *a;//这个指针指向这个类型
Screen &b;
return 0;
}
在类定义中,可以使用另一个类的指针。例如:
class Screen;
class Person
{
public:
private:
Screen *ptr; //ptr指向Screen
Person *a; //指向它自己
};