如何使用指针访问公共结构的变量

时间:2015-03-03 18:54:54

标签: pointers c++11 struct

我有一个指向课程的指针,我试图用它来访问课程'公共结构。我已经查看了access member var using ptr以及access memb struct from ptr class,但是当您查看链接时,它并不是我想要做的。

我在做一些可以构建的事情时遇到了麻烦。代码中的示例没有指针,但我有一个指向IFM的指针。有谁知道如何使用指针(到IFM)来访问公共结构(在IFM中)?

//snippet of code that is trying to access struct in IFM:
const IFM *pJunk = rData1.getM(); //this is fine
pJunk->JunkStruct::Junk.xs; //this doesn't work

The struct in IFM.h:
class IFM final : public IFO
{
public:
    typedef struct JunkStruct
    {
        JunkStruct() = default;
        ~JunkStruct() = default;
        JunkStruct(const IFM::JunkStruct&) = default;
        JunkStruct(const double& first, const double& second, const double& third, const double& fourth, const double& fifth, const double& sixth) :
xs(first), ysk(second), xsk(third), ys(fourth), x(fifth), y(sixth)
            {}
        IFM::JunkStruct& operator=(const IFM::JunkStruct&) = default;

        // Initialized        
        double xs = 1.0;
        double ys = 0.0;
        double xsk  = 0.0;
        double ysk  = 1.0;
        double x = 0.0;
        double y = 0.0;

    } Junk;


...

1 个答案:

答案 0 :(得分:1)

OPs成员是私人的。它被设计为隐藏。这没东西看。

结构只是一种类型。如果IFM中没有成员是JunkStruct类型,那么就没有数据可供访问。要使用该内部类型,您可以看到这个最小的示例

struct Outer
{
    struct Inner{
        int innerMember;
    };
};

int main() {
    Outer::Inner inner;
    inner.innerMember = 4;
    std::cout << inner.innerMember << "\n";

    Outer outer;
    Outer* outerP = &outer;
    outer-> No access to innerMember, it does not exist.
}

另一方面,如果结构不是typedef而只是结构,那么该定义类似于:

struct Outer
{
    struct Inner{
        int innerMember;
    };
    Inner outerMemberInner;  // 
};

int main() {
    Outer outer;
    Outer* outerP = &outer;
    outerP->outerMemberInner.innerMember = 4;
// this might be what you are looking for
    std::cout << outerP->outerMemberInner.innerMember;
}

JunkouterMemberInner

类型JunkStruct别名Junk属于IFM类型,而不属于IFM对象或指针。