如果我有这个泛型方法,那么使用从Foo
派生的参数返回类型string s
对象:
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
方法之后,因此我在createFoo
类定义代码段之后移动Foo
方法并尝试编译。
现在出现新错误:
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 :(得分:0)
您没有包含定义“Foo”的标头,或者您忘记添加using指令以从定义它的命名空间中引入它。
答案 1 :(得分:0)
语句return fooName;
正在返回函数fooName
,我想你打算返回函数调用的结果,它应该像return fooName(first, second, third, fourth, fifth);
答案 2 :(得分:0)
Mert对我的方法位置提出了质疑。方法代码块应该位于文件中的Foo类定义位置之后。
答案 3 :(得分:0)
关于你的第二个错误,转换一个:
Foo fooName(int first, int second,int third,int fourth,int fifth);
您打算创建新的对象实例,将一些参数传递给对象构造函数。但相反,你最终宣布一个新的功能。从参数中删除类型名称(" int" s)以解决此问题。
您还应该了解the most vexing parse。