|
链接提示有问题,请教
complex.h
----------------------------
- #ifndef _COMPLEX_HEADER_
- #define _COMPLEX_HEADER_
- #include <iostream>
- template<class Type>
- class complex
- {
- friend std::ostream& operator << (std::ostream& out, const complex<Type>& complex_num);
- private:
- Type real;
- Type image;
- public:
- complex();
- complex(complex& number);
- complex(Type real, Type image);
- void operator = (const complex& in_number);
-
- public:
- complex& operator + (const complex& add) const;
- Type get_real() const { return real; } ;
- Type get_image() const { return image; } ;
-
- };
- template<class Type>
- std::ostream& operator << (std::ostream& os, const complex<Type>& complex_num);
- template<class Type>
- complex<Type>::complex()
- {
- real = 0;
- image = 0;
- }
- template<class Type>
- complex<Type>::complex(complex<Type>& number)
- {
- real = number.real;
- image = number.image;
- }
- template<class Type>
- complex<Type>::complex(Type in_real, Type in_image)
- {
- real = in_real;
- image = in_image;
- }
- template<class Type>
- complex<Type>& complex<Type>::operator + (const complex<Type>& add) const
- {
- complex<Type> result;
- result.real = real + add.real;
- result.image = image + add.image;
- return result;
- }
- template<class Type>
- void complex<Type>::operator = (const complex<Type>& in_number)
- {
- real = in_number.real;
- image = in_number.image;
- }
- template<class Type>
- std::ostream& operator << ( std::ostream& os, const complex<Type>& complex_num)
- {
- os<<complex_num.real;
- if (complex_num.image > 0) os<<'+';
- if (complex_num.image != 0) os<<complex_num.image<<"i";
- return os;
- }
- #endif //_COMPLEX_HEADER_
复制代码
complex.cpp
------------------------
- #include <iostream>
- #include "complex.h"
- int main()
- {
- complex<int> a(3,5);
- complex<int> b(7,8);
- complex<int> c;
-
- c = a + b;
- std::cout<<"c="<<c.get_real()<<"+"<<c.get_image()<<"i"<<std::endl;
- std::cout<<c;
- return 0;
- }
复制代码
编译输出:
-----------------------------
- waterzh@bing ~ $ g++ complex.cpp
- complex.h:9: 警告:友元声明 ‘std::ostream& operator<<(std::ostream&, const complex<Type>&)’ 声明了一个非模板函数
- complex.h:9: 警告:(如果这不是您原来的想法,请确定此函数模板已经声明过,并在这里的函数名后面添加 <>) -Wno-non-template-friend 禁用此警告
- complex.h: In member function ‘complex<Type>& complex<Type>::operator+(const complex<Type>&) const [with Type = int]’:
- complex.cpp:10: instantiated from here
- complex.h:54: 警告:返回了对局部变量的 ‘result’ 的引用
- /tmp/ccQnC6Iu.o:在函数‘main’中:
- complex.cpp:(.text+0x16c):对‘operator<<(std::basic_ostream<char, std::char_traits<char> >&, complex<int> const&)’未定义的引用
- collect2: ld 返回 1
复制代码 |
|