三个文件
//头文件CStudent.h
#ifndef STUDENT
#define STUDENT
#include
class CStudent
{
public:
CStudent(char* amingzi="mingzi",int axuehao=1);
CStudent(const CStudent& stu);
~CStudent();
char* getname()const;
int getxuehao()const;
private:
char* mingzi;
int xuehao;
};
inline void PrintInfo(const CStudent& stu)
{
std::cout<<"名字:"<
#endif
//CStudent.cpp文件
#include"Cstudent.h"
#include
#include
using namespace std;
CStudent::CStudent(char* amingzi,int axuehao)
{
mingzi=new char[strlen(amingzi)+1];
strcpy(mingzi,amingzi);
xuehao=axuehao;
cout<<"带参构造函数被调用"<
CStudent::CStudent(const CStudent& aCStudent)
{
mingzi=new char[strlen(aCStudent.mingzi)+1];
strcpy(mingzi,aCStudent.mingzi);
xuehao=aCStudent.xuehao;
cout<<"拷贝构造函数被调用"<
CStudent::~CStudent()
{
delete [] mingzi;
cout<<"析构函数被调用"<
char* CStudent::getname()const
{
return mingzi;
}
int CStudent::getxuehao()const
{
return xuehao;
}
//main.cpp文件
#include"CStudent.h"
int main()
{
CStudent a("奥巴马",100);
PrintInfo(a);
CStudent b(a);
PrintInfo(b);
return 0;
}
没有重载=运算符,所以不能b=a;
#include
#include
using namespace std;
class CStudent
{
public:
CStudent(char* n, char* i)
{
strcpy(name, n);
strcpy(id, i);
cout << "带参构造函数被调用" << endl;
}
CStudent(const CStudent& stu)
{
strcpy(name, stu.name);
strcpy(id, stu.id);
cout << "拷贝构造函数被调用" << endl;
}
~CStudent()
{
cout << "析构函数被调用" << endl;
}
void Print()
{
cout << name << " " << id << endl;
}
protected:
char name[20];
char id[20];
};
void PrintInfo(CStudent stu)
{
stu.Print();
}
int main()
{
CStudent stu1("abc", "1234");
CStudent stu2(stu1);
PrintInfo(stu1);
return 0;
}