最近我在只使用网络编程之后一直在学习 C++,到目前为止,通过 cplusplus 教程,一切进展顺利。不过,我一直在努力解决的一件事是使用指针来引用数据结构中的对象。基本上:
string mystr;
movies_t amovie; // create new object amovie from structure movies_t
movies_t* pmovie; // create a new pointer with type movies_t
pmovie = &amovie; // reference address of new object into pointer
cout << "Enter movie title: ";
getline(cin, pmovie->title);
cout << "Enter year: ";
getline (cin, mystr);
(stringstream) mystr >> pmovie->year;
cout << endl << "You have entered:" << endl;
cout << pmovie->title;
cout << " (" << pmovie->year << ")" << endl;
可以像这样简单地编写:
string mystr;
movies_t amovie;
cout << "Enter movie title: ";
getline(cin, amovie.title);
cout << "Enter year: ";
getline(cin, mystr);
(stringstream) mystr >> amovie.year;
cout << endl << "You have entered:" << endl;
cout << amovie.title;
cout << " (" << amovie.year << ")" << endl;
我了解它们在数组中的用途,但我很难理解为什么使用指针比从结构中引用值本身更可取。