Reputation: 919
The following code works fine, when my template class is defined inline:
main
{
unsigned int A=0; //local variable in 'main'.
Test<int> TestObjekt; //Object.
//do something
cout<<TestObjekt.calculate_a(A);
};
The Class is just made 4 test reasons and it adds a '2' to the given data 'a' and it returns the result the local variable 'A' of main:
template <typename T> class Test //dichiarazione classe
{
private:
T a; //private variable of changeable type T.
public:
Test(T InitA) //constructor
{
a=InitA;
}
T calculate_a(T a) //method
{
a+=2;
return a;
}
};
In this way, everything works fine, but when I make an outline definition of the class, the compiler doesn't accept it anymore. Here is the decleration:
template <typename T> class Test //class declaration
{
private:
T a; //private variable
public:
Test(T InitA); //constructor
T calculate_a(T); //method
};
Now my Definitions:
template <typename T> Test<T>::Test(T InitA)
{
a=InitA;
}
template <typename T> T Test<T>::calculate_a(T) //metodo della classe Test
{
a+=2;
return a;
}
The error messages are the following:
1.error C2512: 'Test<T>': non è disponibile alcun costruttore predefinito...
means: there is no appropriate, predefined constructor available
1> with
1> [
1> T=int
1> ]
I'm using the Visual C++ 2008 Express Version Compiler. I'm a C++ beginner and I've neaerly had a nervous breakdown, because I'm already fighting a long time to make the program run.
Hope somebody could help me
Thanks and regards
Uwe
Upvotes: 0
Views: 114
Reputation: 1239
The line Test<int> TestObjekt;
is implicitly calling the default constructor Test<int>()
which doesn't exist.
You either need to add arguments to your constructor call in your main: Test<int> TestObjekt(0);
Or, alternatively, define a constructor that doesn't require a value Test(){ \\do something }
Also the template definitions must be in the header file.
See this answer for a good explanation of why the definitions are required in the header.
Upvotes: 1
Reputation: 1429
In your main function, where an Test object is made, add a value to the constructor (make the TestObject with init-value):
Test<int> TestObjekt(0); // Object with init value
or make a constructor that doesn't require a value, e.g. in your class declaration add a default value to the prototype of the constructor:
Test(T InitA= 0); //constructor with default value
Full version:
template <typename T> class Test //class declaration
{
private: T a; //private variable
public:
Test(T InitA= 0); // <<<-- either change here
T calculate_a(T); //method
};
Or change main:
void main()
{
unsigned int A=0; //local variable in 'main'.
Test<int> TestObjekt(0); // <<<--- change here.
//do something
printf("%d", TestObjekt.calculate_a(A));
};
Upvotes: 1