9

我有一个结构(可以是类)并在另一个类中定义,如图所示

struct A{
somedata_A;
somespecificimplementation_A(someclass *S1);
};

class someclass{
somedata_someclass;
A a;
};

main(){
 someclass c1, *c2;
 c2 = &c1;
 c1.a.somespecificimplementation_A(c2);
}

如何验证 c2 确实是 c1 的参考?请原谅我提出这个例子,因为很明显 c2 是 c1 的参考。

更新:A 不存储指向某个类的指针

4

5 回答 5

6

如果您对父母一无所知,请比较成员的地址

void A::somespecificimplementation_A(someclass *S1)
{
    if (this == &(S1->a)) {
        // parent == S1
    } else {
        // parent != S1
    }
}
于 2013-07-18T07:47:38.433 回答
3

像那样:

struct A{
  int somedata_A;
  int somespecificimplementation_A(someclass *S1){
    if ((void*) &(S1->a) == this)
    {
      std::cout << "S1 is a pointer to myself" << std::endl;
      return 1;
    }
    return 0;
  }
};
于 2013-07-18T07:39:45.423 回答
1

假设struct A有一个指向 的指针c1,那么您可以获取一个指向c2并比较指针值吗?类似于您对赋值运算符重载所做的事情?

于 2013-07-18T07:36:49.923 回答
1

为什么要绕过并将您的类的指针传递给您必须测试的嵌套结构,而您可以在其构造期间由父级提供对父级的引用?

class someclass
{
    public:
        struct a
        {
            void foo()
            {
                parent.doSomething();
            }

            private:
                friend someclass;
                a(someclass & parent)
                : parent(parent)
                {}
                someclass & parent;
        } a;

        someclass() : a(*this) {}

    private:
        void doSomething()
        {
        }
};
于 2013-07-18T07:43:52.877 回答
1

Although technically unspecified, the following will work on most modern, general purpose machines:

void A::somespecificimplementation_A( someclass* S1 )
{
    char const* s = reinterpret_cast<char const*>( S1 );
    char const* t = reinterpret_cast<char const*>( this );
    if ( this >= s && this < s + sizeof( someclass ) ) {
        //  This A is a member of S1
    } else {
        //  This A isn't
    }
}

Having said that, I would stress:

  1. This is not specified by the standard. It will work on machines with a flat, linear addressing, but may fail (give false positives) on a machine with e.g. segmented memory.

  2. I'd seriously question the design if A needs to know who it is a member of.

  3. And if A really does need this information, it really should store a pointer to someclass, which is passed in to its constructor, so that the dependency is manifest.

于 2013-07-18T07:49:03.100 回答