64,670
社区成员
发帖
与我相关
我的任务
分享
// 10xt7.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Teacher
{
public:
class Student;
Teacher();
Teacher(int nu, string na, char s){ num = nu; name = na; sex = s; }
Teacher operator= (Student &);
void display();
private:
int num;
string name;
char sex;
};
class Student
{
public:
Student(int nu, string na, char s){ num = nu; name = na; sex = s; }
friend Teacher;
private:
int num;
string name;
char sex;
};
Teacher Teacher::operator= (Student &stu1)
{
Teacher tea;
tea.num = stu1.num;//这里会显示不允许使用不完整的类型
tea.name = stu1.name;
tea.sex = stu1.sex;
return tea;
}
void Teacher::display()
{
cout << num << endl;
cout << name << endl;
cout << sex << endl;
}
int main()
{
Student stu(123,"Jason",'m');
Teacher tea;
tea = stu;
tea.display();
return 0;
}
Teacher& Teacher::operator= (Student &stu1)
{
num = stu1.num;
name = stu1.name;
sex = stu1.sex;
return *this;
}
Teacher& Teacher::operator= (Student &stu1)
{
num = stu1.num;
name = stu1.name;
sex = stu1.sex;
return this;
}
改成这样
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Student;
class Teacher
{
public:
Teacher(){}
Teacher(int nu, string na, char s){ num = nu; name = na; sex = s; }
Teacher operator= (Student &);
void display();
private:
int num;
string name;
char sex;
};
class Student
{
public:
Student(int nu, string na, char s){ num = nu; name = na; sex = s; }
friend Teacher;
private:
int num;
string name;
char sex;
};
Teacher Teacher::operator= (Student &stu1)
{
Teacher tea;
tea.num = stu1.num;//这里会显示不允许使用不完整的类型
tea.name = stu1.name;
tea.sex = stu1.sex;
return tea;
}
void Teacher::display()
{
cout << num << endl;
cout << name << endl;
cout << sex << endl;
}
int main()
{
Student stu(123, "Jason", 'm');
Teacher tea;
tea = stu;
tea.display();
return 0;
}
看看有什么不同
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(int nu, string na, char s){ num = nu; name = na; sex = s; }
friend class Teacher;
private:
int num;
string name;
char sex;
};
class Teacher
{
public:
Teacher(){};
Teacher(int nu, string na, char s){ num = nu; name = na; sex = s; }
Teacher operator= (Student &);
void display();
private:
int num;
string name;
char sex;
};
Teacher Teacher::operator= (Student &stu1)
{
Teacher tea;
tea.num = stu1.num;//这里会显示不允许使用不完整的类型
tea.name = stu1.name;
tea.sex = stu1.sex;
return tea;
}
void Teacher::display()
{
cout << num << endl;
cout << name << endl;
cout << sex << endl;
}
int main()
{
Student stu(123,"Jason",'m');
Teacher tea;
tea = stu;
tea.display();
return 0;
}
把Student的声明放到Teacher前面,因为Teacher的Teacher operator= (Student &);方法用到了Student &作参数,则在Teacher operator= (Student &);之前必须能看到Student的完整定义才行