Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#include <iostream>

using namespace std;

template<class T>
class Array{
public:
    T U[10];

    friend void DataOut(Array<string>);
    friend void GetData(Array<string>);
};

void DataOut(Array<string> Array1){
    cout << Array1.U[0];
}

void GetData(Array<string> Array1){
    cin >> Array1.U[0];
    cin.clear();
}

int main(){
    Array<string> Arr1;
    GetData(Arr1);
    DataOut(Arr1);
}

I made a class template and created two functions: GetData for entering string and DataOut for printing that string, but after entering string it doesn't print it. What have I done wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

I placed comments where I made changes. The main fix is to pass your object by reference, especially to Getdata(). You passed a copy, put data into the copy, and when the function ended, the copy goes away and your original object was never touched.

#include <iostream>

using namespace std;

template <class T>
class Array {
 public:
  T U[10];

  friend void DataOut(
      const Array<string>&);  // CHANGED: Need to take object by reference
  friend void GetData(Array<string>&);  // SAME
};

void DataOut(const Array<string>& Array1) {  // SAME
  cout << Array1.U[0];
}

void Getdata(Array<string>& Array1) {  // SAME
  cin >> Array1.U[0];
  // cin.clear();  // CHANGED: Why?
}

int main() {
  Array<string> Arr1;
  Getdata(Arr1);
  DataOut(Arr1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...