gpt4 book ai didi

c++ - c++ 中的嵌套类

转载 作者:行者123 更新时间:2023-11-30 02:08:55 25 4
gpt4 key购买 nike

class A{
public:
template<typename Obj>
class MyVec{
//some methods...
};
MyVec<A> a; //-> doesnt work
//vector<A> a; //using stl vector-> this works
};

class B{
public:
void someMethod();
private:
A::MyVec<A> b;
};

在方法中,当我做某事时:

void someMethod(){
//...
b[0].a.pushback(element);
//...
}

在 A 类中,如果我使用 std::vector 一切正常。但是当我使用嵌套类时它不起作用。

最佳答案

我已经获取了您的代码并对其进行了尽可能少的修改以获得可以编译的内容。这似乎工作正常。因此错误不在您向我们展示的代码中。

#include <iostream>
#include <string>

class A
{
public:
template<typename Obj>
class MyVec{
public:
//My pushback just stores the value away for later.
void pushback(Obj & o )
{
if( obj )
{
*obj = o;
}
else
{
obj = new Obj(o);
}
std::cout<<this<<" : Pushing object "<<&o<<std::endl;
}

//some methods...
//My operator[] just returns the stored object.
Obj& operator[](int i) { return *obj; }
Obj * obj;
MyVec() : obj( NULL ) {}
};
MyVec<A> a;
};


class B
{
public:
B()
{
A an_a;
b.pushback(an_a); //Better store one away since we access it in someMethod.
}
void someMethod()
{
//...
A element;
b[0].a.pushback(element);
//...
}
private:
A::MyVec<A> b;
};

int main()
{
//Test that it all works
B outer;
outer.someMethod();
}

当我运行它时,我得到:

0xbffffa5c : Pushing object 0xbffffa0c
0x3ec3c0 : Pushing object 0xbffffa2c

这是我所期望的。 (一次插入 B 的构造函数,一次插入 someThing 的内部对象)

您可以在这里查看结果: http://ideone.com/BX8ZQ

关于c++ - c++ 中的嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com