C++:无法将指针 vector 分配给另一个指针 vector

标签 c++

我有class Student ( studentOwner ) 和 class Section . 这是我的课Student :

class Student {
  vector<Section*> enrolledSections;
public:
  vector<Section*> getEnrolledSections() const { return enrolledSections; }
}

所以,当我得到 vector<Section*>并分配给另一个 vector ,我会遇到错误。我正在使用 Microsoft Visual Studio。

// first example: no error, if take size of vector
int a = studentOwner->getEnrolledSections().size();
// second example: error, when only take its vector and assign again
// Error: no suitable user-define conversion from "std::vector<error-type" ....
vector<Section*> enrolled = studentOwner->getEnrolledSections();
// third example: error when take this vector and assign to reference of same type
// Error: initial value of reference to non-const value must be lvalue
vector<Section*>& enrolled = studentOwner->getEnrolledSections();

第二个例子的完整错误是:

Error: no suitable user-define conversion from "std::vector<error-type", std::alocator<<error-type> *>> "to " std::vector<Section*, std::allocator<Section*>>" exists

在我的项目的许多类中,我无法执行第二行和第三行并收到相同的错误。我自己无法解释。请教我这一点。

谢谢:)

最佳答案

通常如果您看到 error-type在 MSVC 错误中,这是由于未及时包含该编译单元的前向声明类型的结果。例如,

// Course.h
class Student;

class Course {
     [...]
public:
     Student* getStudent();
}

// Course.cpp
#include "Course.h"

Student* Course::getStudent()
{
    return new Student("Name");  //< Whoops, we never included Student.h!
}

在注释中,您指出循环包含依赖项。正如@Daniel Castro 指出的那样,您应该在头文件中转发声明以避免循环包含,然后在您的 .cpp 文件中包含所需的头文件(如果您不熟悉,请注意上面的转发声明 class Student;)。

顺便说一句,我还注意到您的示例存在一些设计问题。返回std::vector<Section*>并没有太多说明谁拥有什么。如果我得到 std::vector根据函数的值,惯例是我现在拥有 vector 及其内容。如果我拥有某些东西,那么我有责任删除它。如果没有看到您的实际实现,大多数编码人员会惊讶地发现他们不应该删除 vector 的内容。我建议通过 const& 返回 vector (例如,const vector<Section*>&)防止客户端代码操纵 vector (因此客户端不拥有它),或使用std::shared_ptr管理您的 Section 的共享所有权计划对象:

class Student {
    vector<shared_ptr<Section>> enrolledSections_;
public:
    vector<shared_ptr<Section>> getEnrolledSections() const { return enrolledSections_; }
}

现在谁拥有什么一目了然。超出您的要求,但希望对您有所帮助。

关于C++:无法将指针 vector 分配给另一个指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505486/

相关文章:

c++ - 在 C++0x 中模拟 finally block

c++ - 为什么用 brew 安装 fmt 和 gcc 编译器后找不到 fmt 库?

c++ - 使用 g++ 编译 C++ 时出现 'hides constructor for' 警告是什么意思?

c++ - 在同一对象中设置私有(private)变量的回调函数

c++ - VoIP:如何从 Qt 多媒体中的摄像头捕获实时音频/视频流字节?

c++ - 寻求概率分布数据表示的建议

C++ GDB Python pretty-print 教程?

c++ - : error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 的错误搜索技巧

c++ - std::string 可以包含嵌入的空值吗?

c++ - 遍历 boost::multi_array 的维度