这样做的正确语法是什么?当然,我犯了一个愚蠢的错误...不幸的是,我试图更好地理解载体。我知道我创建了一个不必要的指针,但我需要理解语法。将对象向量返回给函数
#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*)'
'getVector'听起来像它应该返回一个向量,而不是'otherClass'。 – aschepler
它不清楚你想要做什么。你想从一个函数返回一个向量? – pm100
这个程序可以简化为'std :: cout << 5 << std :: endl;' – myaut