2012-04-23 116 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