2016-04-14 2 views
-3

Я рассмотрел другие вопросы, касающиеся этой ошибки, но до сих пор я не нашел то, что выглядело как ответ на мою проблему. У меня есть два класса: Message и ColorString. В способе бывшего я сделать несколько экземпляров последнего пропускания членов Message конструктору ColorStringC++ недопустимое использование нестатического элемента данных

message.hpp 

#ifndef __MESSAGE__HPP 
#define __MESSAGE__HPP 
#if defined __linux || defined __APPLE__ 
#define UNIXLIKE 
#endif 
//////////////////////////////////////////////////////////////////////////////// 
// Message helps organize error and warning messages       // 
//////////////////////////////////////////////////////////////////////////////// 
#include <iostream> 
#include <sstream> 
#include <fstream> 
#include "color.hpp" 
//////////////////////////////////////////////////////////////////////////////// 
//         MESSSAGE         // 
//////////////////////////////////////////////////////////////////////////////// 
class Message 
{ 
//////////////////////////////////////////////////////////////////////////////// 
public: // types 
//////////////////////////////////////////////////////////////////////////////// 
    typedef COLOR::ColorString           colstr; 
    typedef COLOR::ColorID            color; 
//////////////////////////////////////////////////////////////////////////////// 
public: // methods 
//////////////////////////////////////////////////////////////////////////////// 
    Message(std::ostream& o = std::cerr) 
    : o(std::cerr) 
    { 

    } 
//////////////////////////////////////////////////////////////////////////////// 
    Message(const std::string& message, 
     const std::string& label ="", 
     const std::string file="", 
     const int line = -1, 
     std::ostream& o = std::cerr, 
     const color c = COLOR::RED 
     ) 
    : o(std::cerr) 
    { 

    } 
//////////////////////////////////////////////////////////////////////////////// 
    friend std::ostream& operator<<(std::ostream& o, Message& m) 
    { 
     #ifdef UNIXLIKE 
     colstr lbl(label, c); 
     colstr msg(message); 
     colstr ln(linestr); 
     colstr fl(file); 
     #else 
    std::string lbl(label); 
     std::string msg(message); 
     std::string ln(linestr); 
     std::string fl(file); 
     #endif 
    o << fl << ln; 
    if (fl.size() > 0 || ln.size() > 0) o << ": "; 
    o << lbl << " " << msg << "\n"; 
    o.flush(); 
    return o; 
    } 
//////////////////////////////////////////////////////////////////////////////// 
private: // methods 
//////////////////////////////////////////////////////////////////////////////// 
    void init(const std::string& message, 
      const std::string& label = "", 
      const std::string file="", 
      const int line = -1, 
      std::ostream& o = std::cerr, 
      const color c = COLOR::RED) 
    { 
    this->message = message; 
    this->label = label; 
    this->file = file; 
    this->line = line; 
    this->c = c; 

    if (this->line > -1) 
    { 
     std::stringstream ss; 
     ss << this->line; 
     ss >> linestr; 
    } 

    if (this->file.size() > 0) 
    { 
     this->file = this->file+":"; 
     if (this->line > -1) 
     { 
     this->file = this->file+linestr; linestr=""; 
     } 
    } 
    } 
//////////////////////////////////////////////////////////////////////////////// 
private : // fields 
//////////////////////////////////////////////////////////////////////////////// 
    std::string label; 
    std::string message; 
    std::string file; 
    int line; 
    std::ostream& o; 
    color c; 
    std::string linestr; 
}; 
#endif 

Конструктор ColorString выглядит следующим образом:

/** 
* @brief constructs a ColorString with color @p c and the string 
*  @p s. 
* @param s string to wrap 
* @param c color to print @p s in 
* @param bold determines whether @p s will be printed bold 
*/ 
ColorString(str s, ColorID c=DEF, bool bold=1) 
:string(s), 
color(c), 
bold(bold) 
{ 
} 

Часть вызывает ошибку это:

#ifdef UNIXLIKE 
    colstr lbl(label, c); 
    colstr msg(message); 
    colstr ln(linestr); 
    colstr fl(file); 
    #else 

Ошибки:

message.hpp:58:20: error: invalid use of non-static data member 'label' 
     colstr lbl(label, c); 
        ^~~~~ 
message.hpp:58:27: error: invalid use of non-static data member 'c' 
     colstr lbl(label, c); 
         ^
message.hpp:59:20: error: invalid use of non-static data member 'message' 
     colstr msg(message); 
        ^~~~~~~ 
message.hpp:60:19: error: invalid use of non-static data member 'linestr' 
     colstr ln(linestr); 
        ^~~~~~~ 
message.hpp:61:19: error: invalid use of non-static data member 'file' 
     colstr fl(file); 

В чем проблема?

+1

Не относится к вашей проблеме, но не используйте символы с двойным подчеркиванием в коде. Такие символы зарезервированы для «реализации» (т. Е. Компилятора и стандартной библиотеки). См. [Этот вопрос и ответы] (http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier) ​​для более подробной информации. –

+1

Что касается вашей проблемы, похоже, это может быть связано с [самым неприятным анализом] (https://en.wikipedia.org/wiki/Most_vexing_parse), и компилятор считает, что вы вместо этого провозглашаете прототипы функций. Попробуйте, например. 'colstr lbl = colstr (label, c); вместо этого. –

+0

Спасибо, но такая же ошибка. 'message.hpp: 58: 29: ошибка: недопустимое использование нестатического элемента данных 'label' colstr lbl = colstr (label, c);' –

ответ

2

Проблема в том, что вы определяете функцию friend. Даже когда вы определяете их «inline» в классе, они все еще не являются функциями-членами и нуждаются в экземпляре объекта для доступа к своим членам.

Вам необходимо сделать, например.

colstr lbl(m.label, m.c); 
+0

ах, конечно же, спасибо. –

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