這個問題在這里已經有了答案: 運算子 << 多載 C (1 個答案) 3天前關閉。
我正在使用一個函式void displayStudent(Student stu),它顯示學生的資訊。在我的main()中,我這樣做了(所有引數已經main()分別創建,并且Student是我的類):
Student student1(name1, id1, dept1, year1);
displayStudent(student1);
現在,在我的顯示功能中,這是我的語法,它適用于除name學生之外的所有內容:
void displayStudent(Student stu) {
// Does not work, gives error saying "no type named 'type"
// and no operator "<<" matches these operands.
cout << "Name: " << stu.getName() << endl;
cout << "ID Number: " << stu.getidNumber() << endl;
cout << "Department: " << stu.getDepartment() << endl;
cout << "Year: " << stu.getYear() << endl;;
}
此外,這里的資訊是我的 in 的 getter/setter 函式和nameinStudent.cpp的結構Name,Student.h如下所示:
struct Name {
string firstName;
string lastName;
};
此實體中的變數Student已使用此Student.cpp檔案中另一個函式的隨機資訊初始化:
void Student::setName(Name n) {
name.firstName = n.firstName;
name.lastName = " " n.lastName;
}
Name Student::getName() const {
return name;
}
本質上,我想不通的是,為什么我可以顯示除了name我的main()? 如何解決此問題以訪問name此實體中的結構元素Student?我之前像這樣初始化它們:
Student::Student(Name a, int b, string c, Year d) {
// Assigns student info to the 4 parameter variables
a.firstName = "Roger";
a.lastName = "Federer";
b = 12345;
c = "Art";
d = SENIOR;
name.firstName = a.firstName;
name.lastName = " " a.lastName;
idNumber = b;
department = c;
year = d;
}
uj5u.com熱心網友回復:
在這條線上:
cout << "Name: " << stu.getName() << endl;
stu.getName()回傳一個結構,Name但默認情況下,編譯器不知道如何在使用. 因此,您需要實作自己的多載來列印 a ,例如:Namestd::ostreamstd::coutoperator<<operator<<Name
struct Name {
string firstName;
string lastName;
};
// add this!
ostream& operator<<(ostream &out, const Name &name) {
return out << name.firstName << " " << name.lastName;
}
附帶說明一下,您的Student建構式中有不屬于那里的代碼:
Student::Student(Name a, int b, string c, Year d) {
/* these assignments do not belong here!!! The caller
is responsible for providing the appropriate values
when it calls Student()...
// Assigns student info to the 4 parameter variables
a.firstName = "Roger";
a.lastName = "Federer";
b = 12345;
c = "Art";
d = SENIOR;
For example:
Name name1;
name1.firstName = "Roger";
name1.lastName = "Federer";
int id1 = 12345;
string dept1 = "Art";
Year year1 = SENIOR;
Student student1(name1, id1, dept1, year1);
*/
name.firstName = a.firstName;
name.lastName = /*" " */ a.lastName; // <-- the space character does not belong, either!
// which can be simplified to just this!
// name = a;
idNumber = b;
department = c;
year = d;
}
與相同setName():
void Student::setName(Name n) {
name.firstName = n.firstName;
name.lastName = /*" " */ n.lastName; // <--
// or, simply:
// name = n;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512644.html
標籤:C 功能班级哎呀
