English 中文(简体)
C++: 集装箱原点工
原标题:C++: Container of original pointers

在C++中,我需要储存有关衍生类别的例子。 但是,我认为,如果I m不错,则使用共享接收器到基类的病媒(因为它需要持有不同种类的衍生产品),集装箱必须持有原始点,而不是病媒(或其他中装集装箱)。 在本土C++中是否有这样做的途径,或者我是否必须使用诸如Boston s ptr_vector等特殊集装箱?

EDIT:这是我试验守则:

class Foo
{
public:
    Foo() {}
    virtual ~Foo() {}
    virtual void set_x(int i) = 0;
};

class Bar : public Foo
{
public:
    Bar() {}

    void set_x(int i)
    {
        this->x = i;
    }

    int x;
};

int main()
{
    Bar bar;

    // ptr
    std::cout << &bar << "
";

    std::vector<Foo*> foos;
    foos.push_back(&bar);

    // different ptr value
    std::cout << &foos[0] << "
";

    foos[0]->set_x(1);

    // however, changes are made
    std::cout << bar.x;

    return 0;
}

提前感谢,

jena

最佳回答

在您的上述例子中,你正在印刷的是点人的地址,而不是点人的价值。

而不是:

// different ptr value
std::cout << &foos[0] << "
";

......

// different ptr value
std::cout << foos[0] << "
";

除此以外,您的<代码> 查询和查询;Foo*>将仅作罚款。

问题回答

你们可以制造一个 st子:前导师;foo*> any子会把你交给它。 <>m>won t尽力删除这些销毁点,这可能不是你想要的,但确切地说,它将保持你所传递的价值。

你们还可以制造一个 st子:炉&和lt;共享_和lt;以及,一旦共有的_流体没有红.,就会释放点子。 这些人还将持有你通过的“原始”oo;你可以采用共享的吸收器:植被(a)方法再次获得。

如果你重新使用课堂的多重继承,你将只看到与你衍生的物体完全相同的时间,而且你的基类包括数据。 由于烟.* 最终会提到数据中的“foo”部分,该部分必然是该物体的“root”。

如果您使用<代码>共享_ptr作为您的集装箱成员,每位成员的点人将保留接触原物体的通道。 您可在集装箱内保存之后的任何时间收到一份<代码>共享_ptr的复印件,但原始物体仍将是其目标。

更简单的解决办法是使用<代码>boost:ptr_vector,前提是集装箱内没有两倍出现你的点子——这一设想将带来资源管理的复杂性,并将你发回<编码>共享_ptr。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签