包含内部类的外部类 - 将内部类实例化为外部类的成员

时间:2011-03-27 17:09:45

标签: c++ inner-classes

目前我正在尝试编译以下代码:

terminallog.hh

#ifndef TERMINALLOG_HH
#define TERMINALLOG_HH

#include <string>
#include <sstream>
#include <iostream>

class Terminallog {
public:

    Terminallog();
    virtual ~Terminallog();    

    class Warn {
    public:
        Warn();

    private:
        bool lineended;  
    };
    friend class Terminallog::Warn;

protected:

private:
    Warn warn;     

};

terminallog.cc

 // stripped code

 Terminallog::Terminallog() {
     Warn this->warn();
 }

Terminallog::Warn::Warn() {
    this->lineended = true;
}

//stripped code 

好吧,正如你可能猜到的那样,它失败了;-)。我的编译器说:

g++ src/terminallog.cc inc/terminallog.hh -o test -Wall -Werror 
In file included from src/terminallog.cc:8:
src/../inc/terminallog.hh:56: error: declaration of ‘Terminallog::Warn Terminallog::warn’
src/../inc/terminallog.hh:24: error: conflicts with previous declaration ‘void Terminallog::warn(std::string)’

让我没有选择权。我显然做错了,但我不知道如何解决这个问题。我很感激任何提示。

提前致谢

ftiaronsem

1 个答案:

答案 0 :(得分:2)

Warn this->warn();是无效的C ++语法 - 如果要初始化warn成员,请使用初始化列表(在这种情况下您不需要 - 隐式调用默认构造函数!)

Terminallog::Terminallog() : warn()
{
   // other constructor code
}


// note that `Warn::Warn()` is invoked implicitly on `wake`, so 

TerminalLog::Terminallog() {}

// would be equivalent 
相关问题