类的成员函数定义类外 //类的声明
#include <iostream>
#include<cstring>
//类的成员函数声明放在类内
using namespace std;
class Student
{
public:
void display();
void set_student(int num,const char*name,float score);
private:
int m_num;
char m_name[10];
float m_score;
};
void Student::display()//类的成员函数定义放在类外但一定要指明属于哪个类
{
cout<<m_name<<" 学号是"<<m_num<<" 成绩是"<<m_score<<endl;
}
void Student::set_student(int num,const char*name,float score)
{
m_num=num;
strcpy(m_name,name);
m_score=score;
}
int main()
{
//对象的定义有2种
Student c1;//栈上分配内存
c1.set_student(101,"大贺",100.0);
c1.display();
//堆上分配内存,但使用完必须释放
Student *c2=new Student;
c2->set_student(100,"小贺",99.0);
c2->display();
delete c2;
return 0;
}
2 类的 成员函数定义放在类内 相当于类里面声明内联函数//键盘坏了 ......此代码转载别处
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
private:
int num;
char name[20];
char sex;
public:
void set_data(int n, char *p,char s)
{
num=n;
strcpy(name,p);
sex=s;
}
void display( )
{
cout<<"num: "<<num<<endl;
cout<<"name: " <<name<<endl;
cout<<"sex: " <<sex<<endl<<endl;
}
};
int main()
{
Student stud1,stud2;
stud1.set_data(1,"He",'f');
stud2.set_data(2,"She",'m');
stud1.display();
stud2.display();
return 0;
}