2012-02-03 107 views
0

這就是我所得到的。我試圖在Bar中使用自定義構造函數創建Foo實例。當我嘗試從Bar的構造函數中調用構造函數時,我得到和未解析的外部。無法解析的外部符號「public:class Foo __thiscall Bar :: bu(char const *)」

class Foo 
{ 
public: 
    // The custom constructor I want to use. 
    Foo(const char*); 
}; 

class Bar 
{ 
public: 
    Bar(); 
    //The instance of Foo I want to use being declared. 
    Foo bu(const char*); 
}; 

int main(int argc, char* args[]) 
{ 
    return 0; 
} 

Bar::Bar() 
{ 
    //Trying to call Foo bu's constructor. 
    bu("dasf"); 
} 

Foo::Foo(const char* iLoc) 
{ 
} 
+1

該代碼無效。當你添加一個成員變量的時候,當你想使用一個自定義的構造函數時,它將它作爲一個指針:Foo * bu;然後在構造函數中創建實例。 – peterept 2012-02-03 06:11:07

+0

這是一個鏈接器問題。我認爲你發佈的來源不足以解決你的問題。是否所有內容都在同一個翻譯單元(文件)中聲明?然後我認爲它應該工作。如果沒有,你應該編輯源文件,指出哪些文件存儲在哪個文件中,並給出完整的編譯器和鏈接器命令行以及相應的輸出(在這種情況下不應該那麼多)。 – Axel 2012-02-03 06:12:12

+0

@peterept:我認爲它是有效的,只是Bar :: bu被聲明爲返回Foo而不是成員變量的方法。在Bar :: Bar()中,bu方法被調用,返回一個未使用的對象。沒有多大意義,但應該工作。 – Axel 2012-02-03 06:15:56

回答

0

這可能是你想要什麼:

class Foo 
{ 
public: 
    // The custom constructor I want to use. 
    Foo(const char*); 
}; 

class Bar 
{ 
public: 
    Bar(); 
    //The instance of Foo I want to use being declared. 
    Foo bu; // Member of type Foo 
}; 

int main(int argc, char* args[]) 
{ 
    return 0; 
} 

Bar::Bar() : bu("dasf") // Create instance of type Foo 
{ 
} 

Foo::Foo(const char* iLoc) 
{ 
} 

至於此聲明:Foo bu(const char*);這是一個名爲bu一個成員函數,它接受一個const char*並返回Foo的聲明。未解決的符號錯誤是因爲您從未定義函數bu,但您希望Foo的實例不是函數。

看到評論後,其他方法:

class Foo 
{ 
public: 
    // The custom constructor I want to use. 
    Foo(const char*); 
}; 

class Bar 
{ 
public: 
    Bar(); 
    ~Bar() { delete bu;} // Delete bu 
    //The instance of Foo I want to use being declared. 
    Foo *bu; // Member of type Foo 
}; 

int main(int argc, char* args[]) 
{ 
    return 0; 
} 

Bar::Bar() : bu(new Foo("dasf")) // Create instance of type Foo 
{ 
} 

Foo::Foo(const char* iLoc) 
{ 
} 

而且還有許多其他問題與您的代碼,也許得到一本關於C++一樣C++ Primer將是一個不錯的主意。