问题描述
在这个特定主题上,我已尽力而为地寻找了很多东西.我必须使用大量的变量,也许对于多个对象,然后将它们通过一组函数传递,所以我认为这是最好的方法.
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
}
我是否应该在类中声明一个结构并将该结构用作参数?
Am I supposed to declare a struct in the class and use that struct as the parameter?
推荐答案
事实上,您已经写了所有内容.我只使用 const struct structName&
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 )
{
}
在此声明中
myClass(struct structName);
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.
这篇关于在C ++中将结构作为构造函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!