C ++: بناء جملة للوصول إلى منظم الأعضاء من المؤشر إلى الفصل

StackOverflow https://stackoverflow.com/questions/915106

  •  06-09-2019
  •  | 
  •  

سؤال

أحاول الوصول إلى متغيرات هيكل الأعضاء، لكنني لا يبدو لي أن أحصل على بناء الجملة. أخطاء الترجمة العلاقات العامة. الوصول هي: خطأ C2274: "مصبوب نمط الوظيفة": غير قانوني كجانب يمين ". خطأ المشغل C2228: يسار من "

#include <iostream>

using std::cout;

class Foo{
public:
    struct Bar{
        int otherdata;
    };
    int somedata;
};

int main(){
    Foo foo;
    foo.Bar.otherdata = 5;

    cout << foo.Bar.otherdata;

    return 0;
}
هل كانت مفيدة؟

المحلول

أنت فقط تحدد الهيكل هناك، لا تخصيص واحد. جرب هذا:

class Foo{
public:
    struct Bar{
        int otherdata;
    } mybar;
    int somedata;
};

int main(){
    Foo foo;
    foo.mybar.otherdata = 5;

    cout << foo.mybar.otherdata;

    return 0;
}

إذا كنت ترغب في إعادة استخدام الهيكل في فئات أخرى، فيمكنك أيضا تحديد الهيكل خارج:

struct Bar {
  int otherdata;
};

class Foo {
public:
    Bar mybar;
    int somedata;
}

نصائح أخرى

Bar هو الهيكل الداخلي المحدد في الداخل Foo. وبعد خلق Foo الكائن لا ينشئ ضمنا Barأعضاء. تحتاج إلى إنشاء كائن شريط صريح باستخدام Foo::Bar بناء الجملة.

Foo foo;
Foo::Bar fooBar;
fooBar.otherdata = 5;
cout << fooBar.otherdata;

غير ذلك،

إنشاء مثيل الشريط كعضو في Foo صف دراسي.

class Foo{
public:
    struct Bar{
        int otherdata;
    };
    int somedata;
    Bar myBar;  //Now, Foo has Bar's instance as member

};

 Foo foo;
 foo.myBar.otherdata = 5;

يمكنك إنشاء بنية متداخلة، لكنك لا تخلق أي مثيلات منه داخل الفصل. تحتاج إلى قول شيء مثل:

class Foo{
public:
    struct Bar{
        int otherdata;
    };
    Bar bar;
    int somedata;
};

ثم يمكنك أن تقول:

foo.bar.otherdata = 5;

أنت تعلن فقط FOO :: BAR ولكنك لا تقوم بإبدائها (غير متأكد إذا كان هذا هو المصطلحات الصحيحة)

انظر هنا للاستخدام:

#include <iostream>

using namespace std;

class Foo
{
    public:
    struct Bar
    {
        int otherdata;
    };
    Bar bar;
    int somedata;
};

int main(){
    Foo::Bar bar;
    bar.otherdata = 6;
    cout << bar.otherdata << endl;

    Foo foo;
    //foo.Bar.otherdata = 5;
    foo.bar.otherdata = 5;

    //cout << foo.Bar.otherdata;
    cout << foo.bar.otherdata << endl;

    return 0;
}
struct Bar{
        int otherdata;
    };

هنا قد حددت للتو هيكل ولكن لم يخلق أي كائن منه. وبالتالي عندما تقول foo.Bar.otherdata = 5; إنه خطأ مترجم. إنشاء كائن شريط البنية مثل Bar m_bar; ثم استخدم Foo.m_bar.otherdata = 5;

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top