2011-03-27 125 views
2

目前,我試圖讓下面的代碼進行編譯:外部類內部類 - 實例化內部類作爲外部類的成員

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 

那麼,正如你可能猜到alredy,它的失敗;-)。我的編譯器說:

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

+0

閱讀您的錯誤信息 - 你不發佈正確的代碼 - 你有一個'警告warn'成員變量和一個'警告無效(的std :: string)'成員函數,將其重命名 – Erik 2011-03-27 17:19:17

+0

之一@埃裏克。 Uups,完全正確,並且非常令人印象深刻;-)。這個班裏有更多的代碼,我剝奪了。非常感謝您指出這一點。 – ftiaronsem 2011-03-27 17:26:04

回答

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 
+0

非常感謝您的回答。這非常有趣。我如何從另一個C++文件訪問內部類的方法?我計劃做這樣的事情:Terminallog tlog(); tlog.Warn.PubMethod();來自其他cpp文件。在此先感謝 – ftiaronsem 2011-03-27 17:28:07

+0

哈哈,你已經在你的答案中寫道。我剛剛閱讀了關於初始化列表的教程,然後我注意到了。非常感謝你。你真的值得很快達到10k點;-) – ftiaronsem 2011-03-27 18:18:54

+0

謝謝,在這上面工作;-) – 2011-03-27 18:44:56