#include <iostream> // 你用VC6太旧了我用新的头文件,你还用VC6的话就改回"iostream.h"吧
#include <string>
using namespace std; // 使用命名空间
// 调整声明位置
class Teacher
{
public:
friend class Student; // 设置友元,除非你用某种途径得到name,sex什么的
friend ostream& operator<<(ostream& output, Teacher t);
private:
long num;
string name;
string sex;
};
class Student
{
public:
Student(long num, string name, string sex) :num(num), name(name), sex(sex) {}
// 转换应该是在Student里面
operator Teacher() { Teacher t; t.num = num; t.name = name; t.sex = sex; return t; }
private:
long num;
string name;
string sex;
};
ostream& operator<<(ostream& output, Teacher t)
{
output << "I'm a teacher" << t.name << t.num << t.sex;
return output;
}
int main(int argc, char* argv[])
{
Student s(123, "xiaoming", "man");
cout << Teacher(s); // 强制转换直接输出
return 0;
}
运行效果:
本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。