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
You need to initialise the Sensor instance correctly - for example:
class TestFactor {
public:
TestFactor() : mySensor( 0 ) {}
private:
Sensor mySensor;
};
It works fine for me using c++. Perhaps you didn't declare the construction of Sensor in the initialisation list for Fac?
class Sensor {
public:
Sensor(int *a)
{
}
};
int b;
class Fac {
public:
Fac():
sensor(&b)
{}
private:
Sensor sensor;
};
main()
{
Fac a;
return 0;
}
One thing that I can see is that your constructor for Sensor
is private (try changing class
to struct
or putting public:
before constructor or declaring the frienship between Sensor
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:
class testFactor {
Sensor mySensor;
public:
testFactor() : mySensor(0) {}
};
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.
class Sensor
{
virtual std::string get_sensor_name(void) const = 0;
};
class Fire_Sensor
: public Sensor
{
std::string get_sensor_name(void) const
{ return "Fire Sensor";}
};
Sensor *
Sensor_Factory::create_sensor(std::string name)
{
if (name == "Fire Sensor")
{
return new Fire_Sensor;
}
return NULL;
}
Also look up reference slicing.
精彩评论