Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

Why string is not printed?C++

#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

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

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...