在C ++中通过引用实现矢量指针和传递对象 [英] Vector pointers and passing objects by reference in C++

查看:85
本文介绍了在C ++中通过引用实现矢量指针和传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class Database
{
private:
    vector<myObject*> m_vectorObj;

public: 
    void addObject(myObject &passObj)
}

我正在尝试这样做:

void Database::addObject (myObject &passObj)
{
    m_vectorObj.push_back(passObj);
}

但是给我的错误是没有匹配的函数要调用",我该如何工作并传递对象并存储指针?

But is giving me the error "No matching function to call", how can I make this work and pass the object and store the pointer ?

推荐答案

首先,问问自己是否真的需要使用指针

First of all, ask yourself if you really need to use pointers

如果您这样做,那么您有2个选择.

If you do, then you have 2 options.

m_vectorObj.push_back(&passObj);
                      ^

2:更改功能(从引用更改为指针)

void Database:addObject (myObject *passObj)//pointer to myObject instead of reference
{
    m_vectorObj.push_back(passObj);
}


我完全不会使用指针,但是我建议您将它们封装到 std::unique_ptr


I wouldn't use pointers at all, but i suggest you to encapsulate'em into std::unique_ptr

这篇关于在C ++中通过引用实现矢量指针和传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆