|
发表于 2013-7-7 22:57:26
|
显示全部楼层
- #include <iostream>
- //加上这两行
- class MyClass;
- std::ostream& operator<<(std::ostream& os,MyClass& iClass);
- class MyClass
- {
- public:
-
- MyClass(int *x);
-
- MyClass(const MyClass &rhs);
-
- private:
-
- int *p;
-
- friend std::ostream& operator<<(std::ostream& os,MyClass& iClass);
-
- };
-
- MyClass::MyClass(int *x)
-
- {
-
- p = x;
-
- }
-
- #if 1
-
- MyClass::MyClass(const MyClass &rhs)
-
- {
-
- std::cout << "vice-constructor\n";
-
- *this = rhs;
-
- }
-
- #endif
-
- ///problem one,if I use &rhs instead of rhs,it will prompt an error
-
- std::ostream& operator<<(std::ostream& os,MyClass& rhs)
-
- {
-
- os << *rhs.p << "\n";
-
- return os;
-
- }
-
- int main()
-
- {
-
- MyClass i1( new int(5) );
-
- ///problem two,if I defined a vice-constructor,this override
-
- /// "<<" operator will call my vice-constructor.why?
-
- std::cout << i1;
-
- return 0;
-
- }
复制代码 第一个问题,已经有人说了,我就不说了。第二个问题,你的代码一点问题都没有,出问题的是VC6的编译器。如果使用搞高版本的编译器(VS2003及以上)你的代码就是正确的。如果非要试用报告VC6,则可按照上面的代码在开头增加两行。事实上VC6里友元函数基本都要加类似的这两行(谁让VC6不符合标准呢)。 |
|