2017-04-17 68 views
-6

这样做的正确语法是什么?当然,我犯了一个愚蠢的错误...不幸的是,我试图更好地理解载体。我知道我创建了一个不必要的指针,但我需要理解语法。将对象向量返回给函数

#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*)' 
+0

'getVector'听起来像它应该返回一个向量,而不是'otherClass'。 – aschepler

+0

它不清楚你想要做什么。你想从一个函数返回一个向量? – pm100

+0

这个程序可以简化为'std :: cout << 5 << std :: endl;' – myaut

回答

1

首先,有在这里使用任何指针是没有意义的。没有!

其次,您的获得者应该被限定为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) 

我让你写它的代码。

+0

但是在我的程序中,“obj”是一个指针,因为那时我需要用“delete”来销毁它。 “aClass”是一个指针,出于同样的原因... – nostyn

+1

@nostyn它不应该。这没有理由。 –

+0

所以,如果我想用指针做到这一点,我可以不?为什么?我不能将obj地址传递给函数,并避免不必要地分配更多内存? – nostyn

0

只是说要返回

std::vector<otherClass> *getVector() 
{ 
    return obj; 
} 
什么

std::vector<otherClass> getVector() 
{ 
    return *obj; 
} 
+1

另外,不要在第二种情况下返回一个const引用。 –

+0

我只是想让OP移动一下,显然有很多很多东西错误提供的代码 – pm100

+0

有点在错误的方向... –