簡體   English   中英

重載ostream <<運算符返回地址

[英]Overloading ostream << operator returning address

我正在制作一個從Object派生的簡單Person類。 每個人都有一個名字(字符*)。 我希望能夠使用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_

#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開發人員網絡

如何獲取cout<<p以打印dave

std::ostream& operator<<對於以十六進制格式顯示地址的指針有一個重載(除非它們是指向字符類型的指針,在這種情況下,它假定使用以空值結尾的字符串。)當您說

cout<<p;

因為p是一個指針。 您可以使用其他指針進行測試:

int i = 0;
int* pi = &i;
double d = 3.14;
double* pd = &d;

cout << pi << ", " << pd << '\n';

可以Person*重載operator << ,但是這樣做會非常單調,並使其他C ++用戶感到困惑。

在C ++中要做的正確的事情是不要假裝指向對象的指針就是對象。

如果您希望對象在兩種情況下均能正常工作

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)

您正在完全實現所需的結果。 只需使用

cout << p

調用重載std::ostream& operator<<(std::ostream&, void*) ,該重載顯示指針p指向的地址。

cout << *p

解引用指針並調用您的重載。

您可以提供一個也使用Person* p的運算符。 但是典型的實現方式是在指針前面放一個星號-編譯器無論如何都會簡單地傳遞指針,因為調用使用的是引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM