【发布时间】:2015-01-25 22:19:20
【问题描述】:
我正在制作一个简单的 Person 类,它派生自 Object。 每个人都有一个名字 (char*)。 我希望能够打印使用 cout 的人的姓名。 我没有达到预期的结果。 这是我的代码:
人.h
#include <iostream>
#include <cstring>
#ifndef _PERSON_H_
#define _PERSON_H_
using namespace std;
class Object {};
class Person : public Object {
private:
char* m_name;
public:
Person(char* input);
~Person();
char* getName() const;
//Set to friend because otherwise I was getting a compilation error.
friend ostream& operator<<(ostream& os, const Person& p);
};
#endif // _PERSON_H_
Person.cc
#include "Person.h"
#include <iostream>
#include <cstring>
Person::Person(char* input) {
m_name = new char[strlen(input)];
strncpy(m_name, input, strlen(input));
}
char* Person::getName() const{
return m_name;
}
/*Person& Person::operator=(const Person &rhs) {
delete [] m_name;
m_name = new char[strlen(rhs.getName())];
strncpy(m_name, rhs.getName(), strlen(rhs.getName()));
return *this;
}*/
ostream& operator<<(ostream& os, const Person& p) {
os << p.getName();
return os;
}
Person::~Person() {}
int main() {
char* tmp = "dave";
Person * p = new Person(tmp);
cout<<p;
}
使用上面的代码输出:
0x7fbba3c04b60
如果我将 main 的最后一行更改为:
cout<<*p
我得到了想要的结果,即 dave。
我的参考资料: Microsoft Developer Network
如何让cout<<p 打印dave?
【问题讨论】:
标签: c++ operator-overloading ostream