Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Confused Passing a Struct to Function

Status
Not open for further replies.

jamez05

Programmer
Jul 29, 2005
130
US
I declare the following function:
Code:
    struct DataElement {
       string Fragment;
       double FragVal;
       int   NumFound;

       DataElement()   // Example of a constructor used in a structure.
       {
		Fragment = "";
		FragVal = 0;
		NumFound = 0;
       }
    } *MetaFrag;

I would like to fill in the values in the structure on a different page/function. The other function will do something like:
Code:
    MetaFrag = new DataElement [ 5 ];
    MetaFrag[0].Fragment = "CCCCCCC";
    MetaFrag[0].FragVal = -0.19; 
	MetaFrag[0].NumFound = 0; 

    MetaFrag[1].Fragment = "CCCCCC";
    MetaFrag[1].FragVal = -0.16; 
    MetaFrag[1].NumFound = 0; 
    etc..

I'm thinking I need to pass the address of the structure
in the function. However, I'm getting errors. Can anyone help me with the syntax?
 
> I would like to fill in the values in the structure on a different page/function
If by this you mean a source code file, then you need to put the struct in a header file.

Also, next time, post actual error messages rather than "I get errors", as this tells us nothing.


--
 
I think you've got structures and classes confused.

AFAIK, you can't have a constructor inside a structure. Either the structure (without the constructor) has to go in a header file and the pseudo-constructor goes in the C file with your fill-in function or change your structure to a class including provide get/set functions and create a header file for that.
 
Miros said:
you can't have a constructor inside a structure.
Actually, in C++ structures and classes are virtually identical other than classes have a default private visibility whereas structures have a default public visibility.
However, if you're going to put a constructor in a structure, you might as well make it a class to begin with since you'll probably add other member functions to it later anyways.
 
Just having a constructor that can take your initial values as parameters would probably be an immense help...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top