【发布时间】:2020-03-21 07:45:51
【问题描述】:
所以我对 C++ 非常陌生,我正在处理流和成员函数。我正在尝试使用传递给我的类的值来获得输出,但我没有得到正确的值。相反,我得到了像这样的垃圾值:
( this is the name: , and this is the age: 3223232)
在输出中。这是我的代码:
#include <iostream>
using namespace std;
class Person{
string name;
int age;
public:
ostream& print_on(ostream &o) {
return o << '( this is the name: ' << name << ', and this is the age: ' << age << ')';
}
Person(){
name="noname";
age=0;
}
Person(string name, int age){
name=name;
age=age;
}
void setName(string n) {
name=n;
}
string getName() {
return name;
}
void setAge(int a){
age=a;
}
int getAge(){
return age;
}
friend ostream& operator << (ostream &output,Person &p);
};
ostream& operator << (ostream &output, Person &p){
return p.print_on(output);
}
int main()
{
string name="Helen";
int age=24;
Person p(name,age);
cout<<p;
return 0;
}
【问题讨论】:
-
翻到书中关于成员初始化列表的部分。
-
return o << '( this is the name: '等是一个错误,它应该是字符串周围的双引号。如果您没有收到关于此的编译器警告或错误,请调整您的设置
标签: c++ constructor scope initialization ostream