本文介绍了新手和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我是菜鸟。我试图在学校对象中的一个 向量中存储Student对象指针。 我调用一个setter函数来添加指针。如果我使用这种方法它 有效, 学生st =学生(Randy); 学生* stp =& st; sc.addStudent(stp); 我的问题是将学生转到学校功能。我有一个 重写函数。我尝试从传递的 学生创建一个指针。我打赌那是'我的问题,因为它是副本? 这一切都是因为我想要一个更简洁的方法来做 做这就像大孩子一样: 学生st =学生(Randy); 学生* stp =& st; sc.addStudent(stp); 我读了很多但是我突然忽略了这一点。我在引用 C ++ Primer。 这里'我的输出也是...... 2票据? ahaha ... 学校建设者1 学生构造者2 Randy 超载addStudent1() 学生构造函数2 Biff 重载addStudent3() 学生构造函数2比尔 重载addStudent1() ***列表*** 1 Randy 3 Bill 3 Bill *** EOF *** 按任意键继续。 。 。 main.cpp -------------------------- -------------------------------------------------- ----------- #include< cstdlib> #include< iostream> #include< vector> // #include" Templates.h" // #include" PointersAndReference.h" #include" StudentsAndSchools.h" using namespace std; int main(int argc,char * argv []) { // mypair< intok(10,23); //声明一个INT类w / 构造 // ok.printValues(); // referenceTests(); 学校sc; sc.setNames(" Parkside"); 学生st =学生(Randy ;); 学生* stp =& st; sc.addStudent(stp); sc.addStudent(学生(Biff)); 学生st1 =学生(比尔); 学生* stp1 =& st1; sc.addStudent(stp1); sc.getStudentNames(); system(" PAUSE") ; 返回EXIT_SUCCESS; } --------------- StudentsAndSchools。 h $> ----------------------------------------- -------------------- #ifndef __学生和学校_ #define __学生和学校_ 使用命名空间std; 班级学校; 班级学生{ 私人: static int mLastId; string mName; int mId; School * mSchool; public: 学生(){ cout<< Student Constructor1 << endl; } 学生(字符串n){ cout<< Student Constructor2 << n<< endl; mName = n; mId = ++ mLastId; } void setName(string n ); string getName(); int getId(); }; int Student :: mLastId = 0; string Student :: getName(){return mName; }; int Student :: getId(){return mId; }; 班级学校{ 私人: string mName; 矢量<学生* m学生; 公共: 学校(){ cout<< 学校建设者1 << endl; } void addStudent(Student *); void addStudent(Student&); //重载 函数 void addStudent(学生); void setNames(string n); void getStudentNames(); }; void School :: setNames(string n){ mName = n; } void School :: addStudent(Student * n){ cout<< 重载addStudent1() << endl; mStudents.push_back(n); } void School :: addStudent(Student& n){ cout<< 重载addStudent2() << endl; 学生* s =& n; mStudents.push_back(s); } void School :: addStudent(学生n){ cout<< Overload addStudent3() << endl; 学生* s =& n; mStudents.push_back(s); } void School :: getStudentNames(){ cout<< ***列表*** << endl; for(int i = 0; i< mStudents.size(); i ++) { cout<< mStudents.at(i) - > getId()<< " " << mStudents.at(i) - > getName()<< endl; } cout< < *** EOF *** <<结束; } #endif Hi, I am a noob. I am trying to store Student objects pointers, in avector, within a School object.I call a setter function to add the pointer. If I use this method itworks,Student st = Student("Randy");Student * stp = & st;sc.addStudent(stp); My problem is passing a Student to the School function. I have anoverridden function. I try to create a pointer from the passedStudent. I bet that''s my problem because it''s a copy ? This all came about because I want to have a more succinct method fordoing this, just like the big kids do:Student st = Student("Randy");Student * stp = & st;sc.addStudent(stp); I''ve read lots but am apperantly missing the point. I am referencingthe C++ Primer.here''s my output too ... 2 Bills ?? ahaha ... Schools Constructor 1Student Constructor2 RandyOverload addStudent1()Student Constructor2 BiffOverload addStudent3()Student Constructor2 BillOverload addStudent1()*** List ***1 Randy3 Bill3 Bill*** EOF ***Press any key to continue . . . main.cpp--------------------------------------------------------------------------------------- #include <cstdlib>#include <iostream>#include <vector> // #include "Templates.h"// #include "PointersAndReference.h"#include "StudentsAndSchools.h"using namespace std; int main(int argc, char *argv[]){// mypair<intok(10,23); // Declare an INT class w/construction// ok.printValues();// referenceTests(); School sc;sc.setNames("Parkside"); Student st = Student("Randy");Student * stp = & st;sc.addStudent(stp); sc.addStudent(Student("Biff")); Student st1 = Student("Bill");Student * stp1 = & st1;sc.addStudent(stp1);sc.getStudentNames(); system("PAUSE");return EXIT_SUCCESS;} --------------- StudentsAndSchools.h------------------------------------------------------------- #ifndef __StudentsAndSchools__#define __StudentsAndSchools__ using namespace std;class School; class Student { private:static int mLastId;string mName;int mId;School * mSchool; public:Student(){cout << "Student Constructor1" << endl;}Student(string n){cout << "Student Constructor2 " << n << endl;mName = n;mId = ++mLastId;}void setName(string n);string getName();int getId();};int Student::mLastId = 0; string Student::getName(){ return mName; };int Student::getId(){ return mId; }; class School{ private:string mName;vector<Student*mStudents; public:School(){cout << "Schools Constructor 1" << endl;}void addStudent(Student* );void addStudent(Student &); // overloadedfunctionvoid addStudent(Student); void setNames(string n);void getStudentNames();}; void School::setNames(string n){mName = n;}void School::addStudent(Student* n){cout << "Overload addStudent1()" << endl;mStudents.push_back(n);}void School::addStudent(Student &n ){cout << "Overload addStudent2()" << endl;Student * s = & n;mStudents.push_back(s);}void School::addStudent(Student n ){cout << "Overload addStudent3()" << endl;Student * s = & n;mStudents.push_back(s);} void School::getStudentNames(){cout << "*** List ***" << endl;for(int i=0;i < mStudents.size(); i++){cout << mStudents.at(i)->getId() << " " <<mStudents.at(i)->getName()<<endl;}cout << "*** EOF ***" << endl;}#endif 推荐答案 为什么不保持简单并只使用一个addStudent成员? Why not keep it simple and just use one addStudent member? 你不能使用任何来自std :: You don''t use anything from std:: 不要使用带有双重下划线的守卫,它们是保留的。 Don''t use guards with leading double underscores, they are reserved. 永远不要放一个在标题中使用指令!它将适用于任何包含标题的文件 。 Never ever put a using directive in a header! It will apply in any filethat includes the header. 这些必须声明为内联,或放在源文件中。 These will have to be declared "inline", or placed in a source file. 傻评论! Silly comment! 你不想要这个,这是不明确的。 - Ian Collins。 You don''t want this one, it is ambiguous.--Ian Collins. 在我看来,你应该存储学生,而不是指向 学生。 In my opinion, you should be storing Students, not pointers toStudents. 它的副本好吧,实际上是一个指针的副本,不幸的是 - 复制指针不会复制它的指针。并且指向 对象并不保证该对象继续存在。 这对你来说听起来有点奇怪,但它的基础 C ++中的。一个愚蠢的指针只是一个愚蠢的指针。 Its a copy alright, a copy of a pointer actually, unfortuanately -copying pointers does not copy its pointee. And having a pointer to anobject does not guarentee that the object continues to exist. This may sound a little strange to you right now but its fundamentalin C++. A dumb pointer is just a dumb pointer. 就在这里停止。这应该是你的第一个线索。看看那个 成员函数: void School :: addStudent(学生n){ cout<< ; Overload addStudent3() << endl; 学生* s =& n; mStudents.push_back(s); } 您正在存储指针但参数(学生n)已停止上述成员函数终止后存在 。哑指针指向不再是 的学生。 术语是:悬空指针 结果是:undefined行为 Stop right here. This should be your first clue. Take a look at thatmember function: void School::addStudent(Student n ){cout << "Overload addStudent3()" << endl;Student * s = & n;mStudents.push_back(s);} You are storing pointers and yet parameter (Student n) ceases to existonce the above member function terminates. Dumb pointer points to aStudent that is no longer. The term is: dangling pointerThe result is: undefined behaviour Underscore + Capitale字母保留 2下划线+任何保留的内容 #ifndef学生和学校_h #define StudentsAndSchools_h 虽然学生应该有自己的标题和学校同上 Underscore + Capitale letter is reserved2 Underscores + whatever is also reserved #ifndef StudentsAndSchools_h#define StudentsAndSchools_h Although Student should have its own header and School ditto 在头文件中使用指令是一个非常糟糕的主意。 Using directives in a header file is a very bad idea. 使用init列表初始化非静态成员。 Student(std :: string n):mName(n),mId(++ mLastId) { cout<< Student(std :: string n) << n<< endl; } Initialize non-static members using an init list. Student(std::string n) : mName(n), mId(++mLastId){cout << "Student(std::string n) " << n << endl;} void setName(const std :: string&); void setName(const std::string&); std :: string getName()const; std::string getName() const; int getId()const; int getId() const; //键是常量关键字,唯一需要的版本是 const reference void add(const Student&); //下一个重载防止前者被调用,虽然编译器应该生成一个关于冲突的诊断(其中一个过载,它应该调用吗?)。 /> // the key is the constant keyword, the only version you need is byconst reference void add(const Student&); // the next "overload" prevents the former from being called althoughthe compiler should be generating a diagnostic about a conflict (whichone of these "overloads" should it call?). 上面缺少const限定符 < snip> const qualifiers missing above <snip> 在我看来,你应该存储学生,而不是指向 学生。 In my opinion, you should be storing Students, not pointers toStudents. 这是一个没有指针的例子。请注意学生的副本ctor和 在学校的 ctor中取消注释std :: vector'的预留效果。 #include< iostream> #include< ostream> #include< string> #include< vector> #include< algorithm> #include< iterator> class Student { int id; std :: string name; public: // ctors 学生():id(0),姓名() { std :: cout<< " Student()\ n"; } Student(int i,std :: string n):id(i),name(n) { std :: cout<< " Student(int i,std :: string n)\ n"; } //复制ctor 学生(const学生和复印件) { std :: cout<< 学生(常规学生和副本)\ n;; id = copy.id; name = copy.name; } //朋友op 朋友std :: ostream& operator<<(std :: ostream&,const Student&); }; std :: ostream& operator<<(std :: ostream& os,const Student& r) { os<< id: << r.id; os<< " \tname:" << r.name; return os<< std :: endl; } 班级学校 { static int lastid; std :: string name; std :: vector<学生; 公共: // ctor 学校(std :: string n):姓名(n),学生() { std :: cout<< 学校()\ n;; // students.reserve(64); } //成员函数 void add(const std :: string& s) { students.push_back(学生(++ lastid,s)); } //朋友op 朋友std :: ostream& operator<<(std :: ostream&,const School&); }; int School :: lastid; std :: ostream& operator<<(std :: ostream& os,const School& r) { os<< std :: string(30,'' - ''); os<< \ nnschool: << r.name; os<< \ nstudents: << r.lastid; os<< std :: endl; std :: copy(r.students.begin(), r.students.end(), std :: ostream_iterator< Student>(os)); os<< std :: string(30,'' - ''); 返回os<< std :: endl; } int main() { 学校( The Academy); school.add(Alfred A); school.add(Betty B); school.add(" Carl C"); std :: cout<<学校; } / * 学校() 学生(int i,std :: string n) 学生(const学生和副本) 学生(int i,std :: string n) 学生(const学生和复印件) 学生(const学生和复印件) 学生(int i,std :: string n) 学生(const学生和学生) ;复印件) 学生(const学生和复印件) 学生(常规学生和复印件) --------- --------------------- 学校:学院 学生:3 id:1名称:Alfred A id:2名称:Betty B id:3名称:Carl C --- --------------------------- * / Here is an example without pointers. Note the Student''s copy ctor andthe effects of uncommenting the std::vector''s reserve in the School''sctor. #include <iostream>#include <ostream>#include <string>#include <vector>#include <algorithm>#include <iterator> class Student{int id;std::string name;public:// ctorsStudent() : id(0), name(){std::cout << "Student()\n";}Student(int i, std::string n) : id(i), name(n){std::cout << "Student(int i, std::string n)\n";}// copy ctorStudent(const Student& copy){std::cout << "Student(const Student& copy)\n";id = copy.id;name = copy.name;}// friend opfriend std::ostream& operator<<(std::ostream&, const Student&);}; std::ostream& operator<<(std::ostream& os, const Student& r){os << "id: " << r.id;os << "\tname: " << r.name;return os << std::endl;} class School{static int lastid;std::string name;std::vector< Student students;public:// ctorSchool(std::string n) : name(n), students(){std::cout << "School()\n";// students.reserve(64);}// member functionsvoid add(const std::string& s){students.push_back( Student(++lastid, s) );}// friend opfriend std::ostream& operator<<(std::ostream&, const School&);}; int School::lastid; std::ostream& operator<<(std::ostream& os, const School& r){os << std::string(30, ''-'');os << "\nschool: " << r.name;os << "\nstudents: " << r.lastid;os << std::endl;std::copy( r.students.begin(),r.students.end(),std::ostream_iterator< Student >(os) );os << std::string(30, ''-'');return os << std::endl;} int main (){School school("The Academy");school.add("Alfred A");school.add("Betty B");school.add("Carl C"); std::cout << school;} /*School()Student(int i, std::string n)Student(const Student& copy)Student(int i, std::string n)Student(const Student& copy)Student(const Student& copy)Student(int i, std::string n)Student(const Student& copy)Student(const Student& copy)Student(const Student& copy)------------------------------school: The Academystudents: 3id: 1 name: Alfred Aid: 2 name: Betty Bid: 3 name: Carl C------------------------------*/ 这篇关于新手和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-24 13:23