문제

저는 이 아주 간단한 코드를 컴파일하려고 합니다.

class myList
{
public:
    std::vector<std::string> vec;
    class Items
    {
    public:
        void Add(std::string str)
        {
            myList::vec.push_back(str);
        };
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}

필요한 객체를 더 생성하거나 지나치게 복잡하게 만들지 않고 이 작업을 수행하려면 어떻게 해야 합니까?

도움이 되었습니까?

해결책

부모 클래스에 몇 개의 생성자와 포인터를 추가하십시오.

#include <string>
#include <vector>
class myList
{
public:
    std::vector<std::string> vec;
    myList(): items(this) {} // Added
    class Items
    {
    public:
        Items(myList *ml): self(ml) {}  // Added
        void Add(std::string str)
        {
                self->vec.push_back(str); // Changed
        };
        myList *self; //Added
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}

mylist () 생성자가 필요하므로 내부 클래스 멤버 변수의 인스턴스와 함께 인스턴스를 등록합니다. 그런 다음 외부 마이리스트 클래스 인스턴스에 포인터를 저장하려면 항목 생성자가 필요합니다. 마지막으로 ADD 메소드에서 저장된 MyList 인스턴스에서 VEC를 참조해야합니다.

Catskul이 지적한 것처럼, 항목 생성자는 실제로 수신하는 MyList 포인터로 아무것도하지 않아야합니다. 또한이 답변은 원래 의도에 더 가깝지만 Steveth45의 대답은 실제 프로그램에서하고 싶은 일에 더 가깝습니다.

다른 팁

이렇게하면 수업 회원을 직접 노출시키지 않습니다. 당신의 예는 조금 위조 된 것 같습니다. 왜 std :: 벡터를 클래스에 넣은 다음 공개로 노출합니까?

class myList
{
private:
    std::vector<std::string> vec;
public:
    void Add(std::string str)
    {
        vec.push_back(str);
    };
};

int main()
{
    myList newList;
    newList.Add("A");
}

Java와 달리 C ++의 내부 물체는 외부 '이'포인터에 액세스 할 수 없습니다 ... 생각하면 참조 할 것이없는 경우가있을 수 있습니다.

Richard Quirk의 솔루션은 C ++에서 얻을 수있는 가장 가까운 곳입니다.

내부 클래스는 이름으로 만 관련됩니다. 당신은 그런 기본 클래스에서 벡터를 언급 할 수 없습니다.

벡터를 내부 클래스로 옮기거나 참조를 저장해야합니다.

이 게시물은 몇 년 전이지만 나는 ~할 것 같다 그것에 유용한 것을 추가할 수 있습니다.원본 게시물의 클래스 디자인이 그다지 좋아 보이지 않는다고 말하겠지만, 포함된 클래스에 액세스할 수 있는 포함된 클래스를 갖는 것이 유용한 경우가 있습니다.이는 추가 포인터를 저장하지 않고도 쉽게 수행할 수 있습니다.아래는 예시입니다.일부 기존 코드에서 가져오고 일부 이름을 변경한 것처럼 작동해야 합니다.핵심은 EmbeddorOf 매크로입니다.매력처럼 작동합니다.

//////////////////// .h 파일 /////////////////////////

struct IReferenceCounted
{
    virtual unsigned long AddRef() = 0;
    virtual unsigned long Release() = 0;
};

struct IFoo : public IReferenceCounted
{
};

class Foo : public IFoo
{
public:
    static IFoo* Create();
    static IFoo* Create(IReferenceCounted* outer, IReferenceCounted** inner);

private:
    Foo();
    Foo(IReferenceCounted* outer);
    ~Foo();

    // IReferenceCounted

    unsigned long AddRef();
    unsigned long Release();

private:
    struct EIReferenceCounted : IReferenceCounted
    {
        // IReferenceCounted

        unsigned long AddRef();
        unsigned long Release();
    } _inner;

    unsigned long _refs;
    IReferenceCounted* _outer;
};

///////////////// .cpp 파일 /////////////////

#include <stdio.h>
#include <stddef.h>
#include "Foo.h"

#define EmbeddorOf(class, member, this) \
    (class *) ((char *) this - offsetof(class, member))

// Foo

Foo::Foo() : _refs(1), _outer(&this->_inner)
{
}

Foo::Foo(IReferenceCounted* outer) : _refs(1), _outer(outer)
{
}

Foo::~Foo()
{
    printf("Foo::~Foo()\n");
}

IFoo* Foo::Create()
{
    return new Foo();
}

IFoo* Foo::Create(IReferenceCounted* outer, IReferenceCounted** inner)
{
    Foo* foo = new Foo(outer);
    *inner = &foo->_inner;
    return (IFoo*) foo;
}

// IReferenceCounted

unsigned long Foo::AddRef()
{
    printf("Foo::AddRef()\n");
    return this->_outer->AddRef();
}

unsigned long Foo::Release()
{
    printf("Foo::Release()\n");
    return this->_outer->Release();
}

// Inner IReferenceCounted

unsigned long Foo::EIReferenceCounted::AddRef()
{
    Foo* pThis = EmbeddorOf(Foo, _inner, this);
    return ++pThis->_refs;
}

unsigned long Foo::EIReferenceCounted::Release()
{
    Foo* pThis = EmbeddorOf(Foo, _inner, this);
    unsigned long refs = --pThis->_refs;
    if (refs == 0)
        {

        // Artifically increment so that we won't try to destroy multiple
        // times in the event that our destructor causes AddRef()'s or
        // Releases().

        pThis->_refs = 1;
        delete pThis;
        }
    return refs;
}

건강 상태

다음 구성으로이를 단순화 할 수 있습니다.

typedef std::vector<std::string> myList;

STL 벡터를 직접 사용하지 않는 이유는 무엇입니까? 이렇게하면 모든 표준 알고리즘이 데이터에서 작동하게됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top