Member function cannot access private member

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?

+4
source share
2 answers

Since demo<T> and demo<T1> treated as different types, they may not have access to other personal data.

An easy way to solve this problem is to add a public access function and use it:

 template <typename T> class demo { public: const T &get_data() const { return data; } ... }; template<typename T> template<typename T1> demo<T>::demo(const demo<T1>&k):data(k.get_data()){} 
+8
source

As R Samuel Klatchko answered me, demo<T> and demo<T1> not of the same type.

The solution to your problem was to declare a friend of the other classes:

 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 T1> // This will enable demo<T> and demo<T1> friend class demo ; // to see each other privates as friends // ought to do... }; 
+3
source

Source: https://habr.com/ru/post/1315612/


All Articles