2012-04-23 114 views
1

如果我有這樣的泛型方法,其中利用string s衍生參數返回一個類型Foo對象:返回類型對象的方法

Foo createFoo(string s) 
{ 
    int index, first, second, third, fourth, fifth; 

    Foo fooName(int first, int second,int third,int fourth,int fifth); 
    return fooName; 
} 

然後在主,我嘗試做這樣的事情:

Foo newFoo = createFoo(argv[2]); 

爲什麼編譯器給我這個錯誤?

 
file.cc:30:1: error: ‘Foo’ does not name a type file.cc: In function 
‘int main(int, char**)’: file.cc:180:38: error: ‘createFoo’ was not 
declared in this scope 

來自Java,做這樣的事情通常不會給我任何問題,爲什麼這會成爲C++中的問題?我怎麼能解決這個問題?

編輯1: 一些建議問我的Foo類定義所在的位置。它位於後createFoo方法讓我感動的代碼Foo類定義段後createFoo方法,並試圖編制。 現在出現新的錯誤:

 
file.cc: In function ‘Foo createFoo(std::string)’: file.cc:153:9: 
error: conversion from ‘Foo (*)(int, int, int, int, int)’ to 
non-scalar type ‘Foo’ requested 
+0

你是否將'Foo'的定義包含到你的主源文件中? – suszterpatt 2012-04-23 23:09:23

+2

你在哪裏定義Foo?如果它是在createFoo方法之後,那麼先拿它。 – mert 2012-04-23 23:10:05

+0

Foo的類定義位於相同的.cc文件中。事實上,現在一切都位於同一個文件中。 – 2012-04-23 23:11:22

回答

0

你沒有包含定義「富」的標題,或者你忘了添加使用指令,並從那裏被定義的命名空間拉進去。

0

聲明return fooName;正在恢復功能fooName,我想你打算返回函數調用的結果,應該是這樣的return fooName(first, second, third, fourth, fifth);

0

梅特是正確的質疑我的方法的位置。方法代碼塊應該位於文件中的Foo類定義位置之後。

0

關於你的第二個錯誤,轉換之一:

Foo fooName(int first, int second,int third,int fourth,int fifth); 

要創建新的對象實例,傳遞一些參數給對象的構造。但是,最終你會聲明一個新的函數。從參數中刪除類型名稱(「int」)來解決這個問題。

你也應該知道the most vexing parse