C++类委托构造函数问题
感谢您的阅读。 委托的类称为传感器。它需要在构造函数中设置一个引用,例如:
class Sensor { Sensor(other *ref);}
我有一个类 testFactory。如果我现在输入
class testFactor{ ...东西... 私人的: Sensor mySensor;}
我遇到了所有问题。它不能分配抽象对象。或者它无法声明变量,或者不知道变量的类型。
即使将 Sensor 从标头中取出并作为静态变量放入 cpp 中也无济于事。
仅当我将传感器构造函数更改为空/非构造函数时,我才不会遇到任何问题。
但随后我必须在传感器中使用 setRed 函数,这可能会导致更多问题。
希望你能帮助我:声明一个变量并持有一个带有非 Void 构造函数的类
Thank you for reading.
The to delegate Class is called Sensor. It need a reference to be set in the Constructor like:
class Sensor { Sensor(other *ref);}
I have a Class testFactory. If i now type
class testFactor{
...stuff...
private:
Sensor mySensor;}
I get ALL the Problems. It cannot alloc an abstract Object. Or it cannot declare the variable, or does not know the Type of the variable.
Even taking Sensor out of the header into the cpp with as a static variable does not help.
Only if i change the Sensor Constructor to a void/non Constructor i dont get ANY Problems.
But then i have to use a setRed Function in the Sensor and this could lead to more problems.
Hope you can help me with: declaring a Variable with holds an Class with an non Void Constructor
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要正确初始化传感器实例 - 例如:
You need to initialise the Sensor instance correctly - for example:
对于我来说,使用 c++ 效果很好。也许您没有在 Fac 的初始化列表中声明 Sensor 的构造?
It works fine for me using c++. Perhaps you didn't declare the construction of Sensor in the initialisation list for Fac?
我可以看到的一件事是,您的
Sensor
构造函数是私有的(尝试将class
更改为struct
或将public: 在构造函数之前或声明
Sensor
和包含类之间的友谊)。除此之外,您还应该有一个默认构造函数,或者在包含类中实例化它时提供参数。但显然你需要更具体才能得到更具体的答案。
One thing that I can see is that your constructor for
Sensor
is private (try changingclass
tostruct
or puttingpublic:
before constructor or declaring the frienship betweenSensor
and containing class). And you should either have a default constructor in addition to it or provide the parameter when instantiating it in containing class.But you obviously need to be more specific to get more specific answers.
如果您有带有非默认构造函数的类,编译器将不会为其生成默认构造函数。您也无法实例化仅具有私有构造函数的类。
您可以提供一个公共默认构造函数,使用指向实例的指针,或者只是通过公共构造函数初始化成员:
If you have classes with non-default constructors the compiler wont generate a default constructor for it. You also cannot instantiate classes which have only private constructors.
You can either provide a public default constructor, use a pointer to the instance or simply initialize the member via a public constructor:
还有一点:如果传感器是一个抽象类,则无法创建它的实例。
大多数工厂模式都有一个抽象基类和指向分配的派生对象的基类的返回指针。
另请查找参考切片。
One more point: If sensor is an abstract class, you cannot create an instance of it.
Most factory patterns have an abstract base classes an return pointers of the base class that point to allocated derived objects.
Also look up reference slicing.