2015-04-23 7 views
0

Я работаю над своим проектом, и я хочу перегрузить оператора <<, который должен распечатать мой объект на консоли.
Объект называется «config», и в его классе шаблонов он имеет 4 массива, называемых attribute1, attribute2. attribute3 и attribute4.Оператор << перегрузка

До сих пор я попытался это:

#include "stdafx.h" 
#include <string> 
#include <iostream> 

using namespace std; 

template<typename T> class config 
{ 
    T *attribute1, *attribute2, *attribute3, *attribute4; 
    string attribName1, attribName2, attribName3, attribName4; 
    public: 
    config(void) 
    { 
     attribute1 = new T[3]; 
     attribute2 = new T[3]; 
     attribute3 = new T[3]; 
     attribute4 = new T[3]; 
    } 

    ~config(void)//destruktor 
    { 
     delete [] attribute1, attribute2, attribute3, attribute4; 
    } 

    //operatory 
    friend ostream& operator<<(ostream &out, const config<T> &c); 
};//class ends 

template <typename T> ostream& operator<<(ostream &out, const config<T> &c) 
{ 
    for(int i=0;i<3;i++) 
    { 
    out<<c.attribute1[i]<<c.attribute2[i]<<c.attribute3[i]<<c.attribute2[i]; 
    } 
    return out; 
} 

Всякий раз, когда я пытаюсь скомпилировать его, он дает какие-то странные ошибки, но я знаю, что проблема заключается в операторе.

Это ошибка дает:

Error 1 error LNK2001: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class config<double> const &)" ([email protected][email protected][email protected]@[email protected]@@[email protected]@[email protected][email protected]@@@Z) D:\Docs\Visual Studio 2010\Projects\project_v2.obj project_v2 

и:

Error 2 error LNK1120: 1 unresolved externals D:\Docs\Visual Studio 2010\Projects\project_v2.exe project_v2 

И строка или столбец Isnt указано.

+1

Пожалуйста, включите точное сообщение об ошибке вы получаете, и отметьте, где в источнике этой линии число есть. – aschepler

+3

Обязательно прочтите https://isocpp.org/wiki/faq/templates#template-friends – aschepler

+0

BTW, 'delete [] attribute1, attribute2, attribute3, attribute4;' не удаляет атрибут2', 'attribute3', или 'attribute4'. Вам нужно иметь четыре 'delete []' оператора. –

ответ

1

Вот один из способов решения проблемы.

  1. Объявляет функцию operator<< сначала, перед config определена. Чтобы объявить функцию, вам нужно переслать объявление шаблона класса.

    template <typename T> class config; 
    template <typename T> std::ostream& operator<<(std::ostream &out, 
                   const config<T> &c); 
    
  2. В классе, сделать функцию друга, используя T в качестве параметра шаблона.

    friend ostream& operator<< <T>(ostream &out, const config &c); 
    // Notice this   ^^^^ 
    // This makes sure that operator<< <int> is not a friend of 
    // config<double>. Only operator<< <double> is a friend of 
    // config<double> 
    

Вот рабочая программа с этими изменениями:

#include <string> 
#include <iostream> 

template <typename T> class config; 
template <typename T> std::ostream& operator<<(std::ostream &out, 
               const config<T> &c); 

template <typename T> class config 
{ 
    T *attribute1, *attribute2, *attribute3, *attribute4; 
    std::string attribName1, attribName2, attribName3, attribName4; 
    public: 
    config(void) 
    { 
     attribute1 = new T[3]; 
     attribute2 = new T[3]; 
     attribute3 = new T[3]; 
     attribute4 = new T[3]; 
    } 

    ~config(void)//destructor 
    { 
     delete [] attribute1; 
     delete [] attribute2; 
     delete [] attribute3; 
     delete [] attribute4; 
    } 

    //operator 
    friend std::ostream& operator<< <T>(std::ostream &out, 
             const config &c); 
}; 

template <typename T> std::ostream& operator<<(std::ostream &out, 
               const config<T> &c) 
{ 
    for(int i=0;i<3;i++) 
    { 
     out << c.attribute1[i] << " " 
      << c.attribute2[i] << " " 
      << c.attribute3[i] << " " 
      << c.attribute2[i] << std::endl; 
    } 
    return out; 
} 

int main() 
{ 
    config<double> x; 
    std::cout << x << std::endl; 
} 

Выход:

 
0 0 0 0 
0 0 0 0 
0 0 0 0 

+0

Спасибо, ошибка ушла! – raz

Смежные вопросы