1

I have a library that is written for me in C. In the library there is a variable that I need to use In foo.h (which is in C)

extern mystruct foobar;

In bar.h (which is in C++) I have the following class.

#include foo.h

class myfoo { 

private:
   mystruct foobar;
}

What I would like to know is if I create an array of myfoo, will each instance of foobar be referencing the same variable, or will each instance be its own unique instantiation of the myfoo that independent from the other myfoo foobars?

4

3 に答える 3

5

Here’s the deal: you are not using foo.h’s foobar variable in bar.h (this is particularly true because foo.h only declares foobar, a definition would have to be in an implementation file). Rather, you are redeclaring a variable with the same name and type in the scope of the class.

With that, all the normal rules for an instance member variable apply. In particular, every instance of myfoo will have its own instance of foobar.

If you removed the declaration from foo.h nothing would change: the declaration is completely irrelevant for your bar.h file.

于 2012-12-21T01:01:13.763 に答える
3

The foobar member inside the class definition of myfoo is defined at a different scope from the foobar at global scope. The are different variables, unrelated to each other, except that they are of the same type, and happen to have the same name (although at different scopes).

If you create an array of myfoo objects, each one will have an instance of mystruct. All of those instances will be separate from the one declared in the global scope.

于 2012-12-21T01:01:36.060 に答える
0

What I would like to know is if I create an array of myfoo, will each instance of foobar be referencing the same variable, or will each instance be its own unique instantiation of the myfoo that independent from the other myfoo foobars?

if you do this:

#include foo.h

class myfoo 
{ 
private:
    mystruct foobar;
};

void func()
{
    myfoo f[3];
    // ...
}

you create 3 different myfoo objects, each with its own foobar instance.

if you change the myfoo declaration as follows:

#include foo.h

class myfoo 
{
private:
   static mystruct foobar;
};

// this extra declaration is required for 
// static member variables
mystruct myfoo::foobar;

void func()
{
    myfoo f[3];
    // ...
}

then the three instances of myfoo will share their single instance of foobar.

NOTE:

The class myfoo declaration may be in either a '.h' or a '.cpp' file.

The mystruct myfoo::foobar; declaration may only appear once, so it normally has to be in a '.cpp' file (or '.cc' or whatever you use).

于 2012-12-21T01:49:25.687 に答える