c++ - 如何在 C++ 中定义特定于类的 << 运算符

标签 c++

给定一个类,例如:

class Person
{
private:
    char *name;

public:
    Person()
    {
        name = new char[20];
    }
    ~Person()
    {
        delete [] name;
    }
}

我想使用如下语句从 this 的一个实例打印名称:

cout << myPerson << endl;

我需要做什么来定义 <<此类的输出运算符?

最佳答案

在类中添加:

friend std::ostream& operator<< (std::ostream& out, const Person& P);

然后定义运算符<<是这样的:

std::ostream& operator<< (std::ostream& out, const Person& P) {
    out << P.name;
    return out;
}

关于c++ - 如何在 C++ 中定义特定于类的 << 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/907620/

相关文章:

c++ - 如何在C++中的给定索引处插入列表中的项目

c++ - 从 std 包装 C++ 功能有时是个坏主意?

c++ - 使用 Adaboost 的决策树/树桩

C++ 嵌套作用域访问

c++ - 错误 : no matching function for call to ‘min(long unsigned int&, unsigned int&)’

c++ - 使用 clang 优化进行编译时出现意外结果

c++ - 结构给出不正确的输出

c++ - 使用 WideCharToMultibyte 时如何删除控制字符

c++ - curl_easy_getinfo undefined symbol 错误

c++ - 像 C++ 一样编写高效的实体系统