以下类模板给出了编译错误:
template <typename T> class foo
{
T attribute1;
std::vector<foo*> attribute2;
public:
foo(const T& data):attribute1(data){}
// Some methods
foo* getAttribute2(int pos)const
{
if (pos<0 || pos>=attribute2.size())
throw "In foo::getAttribute2, argument out of range";
return attribute2[pos];
}
void append(foo<T>* element) {attribute2.push_back(element);}
void foo2vector(std::vector<T>& v)
{
v.push_back(attribute1);
if (attribute2.size()>0)
{
for(int i=0; i<attribute2.size();i++)
attribute2[i]->foo2vector(v);
}
}
void display3()const
{
std::vector<T> v;
foo2vector(v);
std::reverse(v.begin(),v.end());
for (int i=0;i<v.size();i++)
std::cout<<v[i]<<"\t";
}
};
foo2vector
方法的想法是将attribute1
放在向量中,以及attribute1
中存储的所有元素的所有attribute2
(它们是有限的) )。
在v.push_back(attribute1)
行中,我有错误:
Reference to type const value_type(aka foo<int> *const) could not bind to an rvalue of type const foo<int>*
当我在int
中使用main
的课程时。
foo<int>* root=new foo<int>(12);
root->append(new foo<int>(8)); // node 0
root->append(new foo<int>(23)); // node 1
// Sons of node 0
(root->getAttribute2(0))->append(new foo<int>(4));
(root->getAttribute2(0))->append(new foo<int>(9));
// Sons of node 1
(root->getAttribute2(1))->append(new foo<int>(17)); // node 4
root->display3();
答案 0 :(得分:0)
这是一个有效的例子,因为你的编辑没用。
#include <iostream>
#include <vector>
template <typename T> class foo
{
T attribute1;
std::vector<foo*> attribute2;
public:
foo(const T& data):attribute1(data){}
// Some methods
foo* getAttribute2(int pos)const
{
if (pos<0 || pos>=attribute2.size())
throw "In foo::getAttribute2, argument out of range";
return attribute2[pos]; // One can also use "return sons.at(pos)" which handles itself range problems
}
void foo2vector(std::vector<T>& v)
{
v.push_back(attribute1);
if (attribute2.size()>0)
{
for(unsigned int i=0; i<attribute2.size();i++)
attribute2[i]->foo2vector(v);
}
}
};
int main()
{
foo<int> f(5);
std::vector<int> v;
f.foo2vector(v);
std::cout << "ok" << std::endl;
return 0;
}
<强> Live On Coliru 强>
所以请记住这个例子并尝试处理你的逻辑。
另请注意,我在for循环中使用了unsigned int
,以消除警告(使用-Wall
)。
提示:我没有downvote,但这是因为您的代码中没有帮助的编辑和最初的拼写错误。
答案 1 :(得分:0)
一切都很好,除了很少的东西
foo(const T& data):attribute(data){} is wrong it should be
foo(const T& data):attribute1(data){}
^^
语法错误在课程结束时
template <typename T> class foo
{
T attribute1;
std::vector<foo*> attribute2;
public:
foo(const T& data):attribute1(data){}
// Some methods
void foo2vector(std::vector<T>& v)
{
v.push_back(attribute1);
if (attribute2.size()>0)
{
for(int i=0; i<attribute2.size();i++)
attribute2[i]->foo2vector(v);
}
}
}; //it was missing please correct
请参阅解决方案链接http://ideone.com/gXqRbm
答案 2 :(得分:0)
这是const正确性中的一个简单错误。 display3
为const
,但您在其中调用foo2vector()
,而不是const
。 ideone's gcc生成的错误消息非常有用。要解决此问题,只需将foo2vector()
标记为const
:
void foo2vector(std::vector<T>& v) const
{
v.push_back(attribute1);
if (attribute2.size()>0)
{
for(unsigned int i=0; i<attribute2.size();i++)
attribute2[i]->foo2vector(v);
}
}