简体   繁体   中英

Passing a struct as a constructor parameter in C++

I've looked as best I can and can't find much on this particular topic. I have to take a large number of variables, maybe for more than one object and pass them through a set of functions so I think this is the best way to do it.

I'd like to pass a struct to a constructor for a class where the struct is not defined. Is this possible? My code looks something like this:

class myClass
{
protected:
   double someVar;
   .
   .
public:
   myClass(struct structName);  //compiler is ok with this
   myClass();                   //default construct
};

struct structName
{
   double someOtherVar;
   .
   .
};

myClass::myClass(??????)  ///I don't know what goes here
{ 
  someVar = structName.someOtherVar; ///this is what I want to do
} 

EDIT: Am I supposed to declare a struct in the class and use that struct as the parameter?

In fact you already wrote all. Only instead of struct structName I would use const struct structName &

myClass::myClass( const structName &s )
{ 
  someVar = s.someOtherVar; 
} 

Or you could define the constructor as

myClass::myClass( const structName &s ) : someVar( s.someOtherVar )
{ 
} 

In this declaration

   myClass(struct structName);  

struct structName is so-called elaborated type name. It introduces a new type in the namespace where the class is defined.

In your example you at first declared the structure and then defined it. The constructor declaration does not require that the structure would be a complete type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM