Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 过载ostream<&书信电报;接线员回邮地址_C++_Operator Overloading_Ostream - Fatal编程技术网

C++ 过载ostream<&书信电报;接线员回邮地址

C++ 过载ostream<&书信电报;接线员回邮地址,c++,operator-overloading,ostream,C++,Operator Overloading,Ostream,我正在制作一个简单的Person类,它派生自Object。 每个人都有一个名字(char*)。 我想能够打印的人的名字使用cout。 我没有达到预期的结果。 这是我的密码: 人 #include <iostream> #include <cstring> #ifndef _PERSON_H_ #define _PERSON_H_ using namespace std; class Object {}; class Person : public Object { p

我正在制作一个简单的Person类,它派生自Object。 每个人都有一个名字(char*)。 我想能够打印的人的名字使用cout。 我没有达到预期的结果。 这是我的密码:

#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_
如果我将干管的最后一行更改为:

cout<<*p

cout
std::ostream&operator您正获得您想要的结果。简单使用


cout您可以重载
operator您还可以提供一个接受
Person*p
的operator。但是典型的实现是在指针前面放一个星号,编译器将简单地传递指针,因为调用正在使用引用。

如果您希望对象在这两种情况下都工作

cout << p ;
cout << *p;

我不能谢谢你。我将重载函数接收的参数更改为指针:
friend-ostream&operator@Airwavezx你真的不应该那样做。你应该让指针作为指针打印出来。我编辑了这行,它应该是
*p
而不仅仅是
p
。可以吗?不,你真的不应该那样做。你应该让指针作为指针打印出来,这就是我所做的。虽然上面有人提到这不是一个好主意。很抱歉,我没有看到你的评论。我认为这是问题的解决方案,但这不是最好的主意,但通常情况下,如果您将指针作为常量传递,则可以确保指针已初始化
cout<<*p
cout<<p;
int i = 0;
int* pi = &i;
double d = 3.14;
double* pd = &d;

cout << pi << ", " << pd << '\n';
cout << p ;
cout << *p;
friend ostream& operator<<(ostream& os, const Person* p);

ostream& operator<<(ostream& os, const Person* p) {
    os << p->m_name << "\n";
    return os;
}
friend ostream& operator<<(ostream& os, const Person* p)
friend ostream& operator<<(ostream& os, const Person p)