注册 登录
编程论坛 C++教室

一道类的强制类型转换题,请帮忙!operator

zsh0435 发布于 2005-05-26 23:56, 1191 次点击

#include<iostream.h> class Cat; class Person { public: int age; }; class Cat { public: int age; };

void main(void) { Person p1; p1.age=50; Cat c1; c1=p1; cout<<c1.age<<endl; } 请问如何将Person类强制转换成Cat类,使c1=p1覆值成功

5 回复
#2
当当2005-05-27 10:26
将等号重载就行了啊。
cat opeator =(Person p1)
{
         Cat temp;
         temp.age = p1.age;      
         return temp;
}

#3
当当2005-05-27 10:26
不知道对不对哦。
#4
zsh04352005-05-27 17:36

谢谢楼上的兄台。我已经搞定了 #include<iostream.h> class Cat { public: int age; /*operator =(Person p) { age=p.age; }*/ Cat(int age) { this->age=age; } }; class Person { public: int age; Person(int age) { this->age=age; } operator Cat() { return Cat(this->age); }

}; void main(void) { Person p1(20); Cat c1(10); c1=p1;//1> c1=(Cat)p1; 2> c1=p1 cout<<c1.age<<endl; }

#5
当当2005-06-03 21:18

#include<iostream.h> class Cat; class Person { public: int age; };

class Cat { public: int age; Cat &operator =(Person p1) { Cat temp; temp.age = p1.age; return temp; } };

void main() { Person p1; Cat c1; p1.age = 50; c1=p1; cout<<c1.age<<endl; } 我用c free 3.5 结果为575,怪怪

#6
zhou2008-03-30 11:39
提示: 作者被禁止或删除 内容自动屏蔽,只有管理员可见
1