类的定义,成员函数和内置成员函数

目录

类的定义:

类的权限修饰符:

 类定义对象的方法:

类成员函数:

成员函数的存储方式:

对象成员的引用:


类的定义:

  1. 类是对象的抽象,而对象是类的具体实例;

  2. 类是抽象的,不占用内存;对象是具体的,占用内存

  3. 结构体是一种特殊的类,是权限为public的类

  4. 类中如果没有给出权限修饰,模式是private

类的权限修饰符:

public:

类外可见

C++结构体,是public的类

protected:

 类内及子类可见

友元函数可见

private:

 类内可见

友元函数可见

 类定义对象的方法:

  1.  class 类名 对象        //大程序中使用,尽量使用这种,保持良好的习惯
  2. 类名 对象                  //小程序中使用
  3. class

         {

        } 对象                          //无类名的对象

类成员函数:

成员函数:类内声明,类外定义,需要类名::

若声明中有默认参数,则得定义中需要添加(若添加的错误提示是:重定义默认参数 : 参数  1等)

class Student
{
public:
	void display(int num = 5,string name = "Chaoren",char sex = 'f' );
private:
	int num;
	string name;
	char sex;
};
void Student::display(int num  ,string name,char sex){
		cout<<"num:"<<num<<endl;
		cout<<"name:"<<name<<endl;
		cout<<"sex:"<<sex<<endl;
	}

内置成员函数:

在C++ 类内定义的内置成员函数,已经默认是内置成员成员函数

            类外定义的内置成员函数,需要有inline作显示声明,否则不是;

            类外定义的的内置成员函数,必须要把函数的声明和定义放在同一个头文件中

class Student
{
public:
	//类内定义默认是内置成员函数,inline可以不加
	inline void show(){
		cout<<"num:"<<num<<endl;
		cout<<"name:"<<name<<endl;
		cout<<"sex:"<<sex<<endl;
	}
	inline void display(int num = 5,string name = "Chaoren",char sex = 'f' );//类内声明,必须加inline
private:
	int num;
	string name;
	char sex;
};
//类外定义,必须加inline
inline void Student::display(int num  ,string name,char sex = 'f' ){
		cout<<"num:"<<num<<endl;
		cout<<"name:"<<name<<endl;
		cout<<"sex:"<<sex<<endl;
	}

成员函数的存储方式:

每个对象的数据成员独立占用空间,而函数代码占用公共空间

一个对象占有存储空间 = 对象的数据成员的存储空间

注意:

  1. 成员函数(无论是类内定义还是类外定义)的代码段的存储方式是相同的,都不占对象的存储空间
  2. 不论时候inline 声明,成员函数的代码段的都不占用对象的存储空间

对象成员的引用:

  1. 通过对象名和成员运算符访问对象中的成员
  2. 通过指针对象的指针访问对象中的成员
  3. 通过对象的引用访问对象中的成员

 代码1

#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
	//类内定义默认是内置成员函数,inline可以不加
	inline void show(){
		cout<<"num:"<<num<<endl;
		cout<<"name:"<<name<<endl;
		cout<<"sex:"<<sex<<endl;
	}
	inline void display(int num = 5,string name = "Chaoren",char sex = 'f' );//类内声明,必须加inline
private:
	int num;
	string name;
	char sex;
};
//类外定义,必须加inline
inline void  Student::display(int num  ,string name,char sex){
		cout<<"num:"<<num<<endl;
		cout<<"name:"<<name<<endl;
		cout<<"sex:"<<sex<<endl;
	}
int main(){
	class Student *stu1 = new Student;
	stu1->display();

	class Student stu2 ;
	stu2.display();
	system("pause");
	return 0;
}

代码2:

#include<iostream>
#include<string>
using namespace std;
class Time
{
public:
	void setTime();
	void getTime();
private:
	int hour;
	int min;
	int sec;
};
void Time::setTime(){
	cin>>this->hour;
	cin>>this->min;
	cin>>this->sec;
}
void Time::getTime(){
	cout<<this->hour<<":"<<this->min<<":"<<this->sec<<endl;
}
int main(){
	class Time time1;
	time1.setTime();
	time1.getTime();
	system("pause");
	return 0;
}

发布了114 篇原创文章 · 获赞 28 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/ChaoFeiLi/article/details/103605216