将对象向量返回给函数
问题描述:
这样做的正确语法是什么?当然,我犯了一个愚蠢的错误...不幸的是,我试图更好地理解载体。我知道我创建了一个不必要的指针,但我需要理解语法。将对象向量返回给函数
#include <iostream>
#include <vector>
class otherClass
{
public:
otherClass(int x):value(x)
{
//ctor
}
int getValue()
{
return value;
}
private:
int value;
};
class MyClass
{
public:
MyClass(int x)
{
obj = new std::vector<otherClass>(x,otherClass{5});
}
otherClass getVector()
{
return obj; //HERE FIRST ERROR <---------------
}
private:
std::vector<otherClass>*obj;
};
void doSomething(otherClass*obj)
{
std::cout << obj->getValue() << std::endl;
}
int main()
{
MyClass*aClass = new MyClass(10);
doSomething(aClass->getVector()); //HERE SECOND ERROR <---------------
return 0;
}
错误编译时,我得到:
第一:
error: invalid conversion from 'std::vector<otherClass>*' to 'int' [-fpermissive]
二:
error: cannot convert 'otherClass' to 'otherClass*' for argument '1' to 'void doSomething(otherClass*)'
答
首先,有在这里使用任何指针是没有意义的。没有!
其次,您的获得者应该被限定为const
,并返回像矢量这样的重物的const引用。它可以防止无用的副本。
int getValue() const
// ^^^^^
{
return value;
}
内otherClass
和
class MyClass
{
public:
MyClass(int x) : obj(x, otherClass{5}) // construction here
{ }
std::vector<otherClass> const & getVector() const
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^
{
return obj;
}
private:
std::vector<otherClass> obj; // no pointer, just a vector
};
然后在主:
MyClass aClass(10);
你想与doSomething()
做什么还不清楚。用您的代码doSomething(aClass->getVector())
您应该处理otherClass
es的返回矢量。所以它应该是:
void doSomething(std::vector<otherClass> const & obj)
我让你写它的代码。
答
只是说要返回
std::vector<otherClass> *getVector()
{
return obj;
}
什么
或
std::vector<otherClass> getVector()
{
return *obj;
}
'getVector'听起来像它应该返回一个向量,而不是'otherClass'。 – aschepler
它不清楚你想要做什么。你想从一个函数返回一个向量? – pm100
这个程序可以简化为'std :: cout myaut