I have the following code
#include <iostream> #include <string> template <typename T> class demo { T data; public: demo(); demo(demo const&k ); demo(const T&k); demo& operator=(const demo &k); template<typename T1> demo(const demo<T1>&k); template<typename T1> demo<T>& operator=(const demo<T1>&k); ~demo(); }; template <typename T> demo<T>::demo():data(){} template<typename T> demo<T>::demo(demo const& k):data(k.data){} template<typename T> demo<T>::demo(const T&k):data(k){} template<typename T> demo<T>& demo<T>::operator=(demo const &k) { if ((void*)this == (void*)&k) { // assignment to itself? return *this; } this->data=k.data; return *this; } template<typename T> template<typename T1> demo<T>& demo<T>::operator=(demo<T1> const &k) { if ((void*)this == (void*)&k) { // assignment to itself? return *this; } this->data=k.data; return *this; } template<typename T> template<typename T1> demo<T>::demo(const demo<T1>&k):data(k.data){} template<typename T> demo<T>::~demo(){} int main() { demo<std::string> k(std::string("hello")); demo<std::string >l=k; demo<int> x(10); demo<double> p=x; //error here }
Why am I getting an error here? As far as I know, p copied to x . So,
demo<T>::demo(const demo<T1>&k):data(k.data){}
Called
. But since data is a private member, I get the error message 'demo<T>::data' : cannot access private member declared in class 'demo<T>' . What for?
I know that class member functions can access private members, so why can I get an error message? What should I do to fix the error?
source share