将对象的向量返回到函数
return vector of objects to a function
正确的语法是什么?当然,我犯了一些愚蠢的错误...不幸的是,我正在努力更好地理解向量。我知道我创建了一个不必要的指针,但是我需要了解语法。
#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;
}
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量