将对象的向量返回到函数

return vector of objects to a function

本文关键字:函数 返回 向量 对象      更新时间:2023-10-16

正确的语法是什么?当然,我犯了一些愚蠢的错误...不幸的是,我正在努力更好地理解向量。我知道我创建了一个不必要的指针,但是我需要了解语法。

#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;
}