在 C++ 中使用运算符重载

发布于 2024-10-02 20:09:25 字数 439 浏览 3 评论 0原文

class A
{
public:
    ostream& operator<<(int  string)
    {
        cout << "In Overloaded function1\n";
        cout << string << endl;
    }
};

main()
{
    int temp1 = 5;
    char str = 'c';
    float p= 2.22;
    A a;
    (a<<temp1);
    (a<<str);
    (a<<p);
    (a<<"value of p=" << 5);
}

我希望输出为: p=5 的值

应该做什么更改...并且该函数应该接受传递的所有数据类型

class A
{
public:
    ostream& operator<<(int  string)
    {
        cout << "In Overloaded function1\n";
        cout << string << endl;
    }
};

main()
{
    int temp1 = 5;
    char str = 'c';
    float p= 2.22;
    A a;
    (a<<temp1);
    (a<<str);
    (a<<p);
    (a<<"value of p=" << 5);
}

I want the output to be: value of p=5

What changes should is do...and the function should accept all data type that is passed

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七颜 2024-10-09 20:09:25

有2种解决方案。

第一个解决方案是使其成为模板。

            template <typename T>
            ostream& operator<<(const T& input) const
            {
                    cout << "In Overloaded function1\n";
                    return (cout << input << endl);
             }

但是,这将使 a << stra << p 打印 c2.22,这与您的原始代码不同。输出 992

第二种解决方案是简单地为 const char* 添加一个重载函数:

            ostream& operator<<(int  string)
            {
                    cout << "In Overloaded function1\n";
                    return (cout << string << endl);
             }

            ostream& operator<<(const char*  string)
            {
                    cout << "In Overloaded function1\n";
                    return (cout << string << endl);
             }

这允许 C 字符串和所有可转换为 int 的内容成为 A << >'ed,但仅此而已 - 它不会“接受传递的所有数据类型”。


顺便说一句,您忘记返回 ostream

There are 2 solutions.

First solution is to make it a template.

            template <typename T>
            ostream& operator<<(const T& input) const
            {
                    cout << "In Overloaded function1\n";
                    return (cout << input << endl);
             }

However, this will make the a << str and a << p print c and 2.22, which is different from your original code. that output 99 and 2.

The second solution is simply add an overloaded function for const char*:

            ostream& operator<<(int  string)
            {
                    cout << "In Overloaded function1\n";
                    return (cout << string << endl);
             }

            ostream& operator<<(const char*  string)
            {
                    cout << "In Overloaded function1\n";
                    return (cout << string << endl);
             }

This allows C strings and everything convertible to int to be A <<'ed, but that's all — it won't "accept all data type that is passed".


BTW, you have forgotten to return the ostream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文