【问题标题】:Defining operator<< Inside Class在类中定义 operator<<
【发布时间】:2011-03-03 03:13:27
【问题描述】:

考虑以下代码:

class MyClass
{
    template <typename Datatype>
    friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);
    // ...
};

template <typename Datatype>
MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData)
{
    // ...
}

我怎样才能在类中定义operator&lt;&lt;内部,而不是作为友元函数?像这样的:

class MyClass
{
    // ...

    public:

    template <typename Datatype>
    MyCLass& operator<<(MyClass& MyClassReference, Datatype SomeData)
    {
        // ...
    }
};

上面的代码会产生编译错误,因为它接受两个参数。删除 MyClassReference 参数可修复错误,但我有依赖于该参数的代码。 MyClassReference 是否仅相当于 *this

【问题讨论】:

  • MyClass 是采用DataType 类型参数的模板吗?
  • @大卫不;出于演示目的,Datatype 用于代替实际类型。
  • @Maxpm:那你为什么要在看起来像是定义的地方添加template?您正在声明一个朋友函数,但定义一个模板,它是一个不同的野兽,因此不是朋友。
  • @David 所以插入操作符可以接受任何类型的输入。
  • 然后成为模板,而不是函数。 template &lt;typename T&gt; void foo( T ); 是模板,void foo( int ); 是函数,f(1) 是对非模板函数的调用,f&lt;int&gt;(5) 是对模板函数的调用。它们是不同的东西,因此您不能与其中一个成为朋友并期望另一个可以访问。我在下面添加了一个答案。如果这还不够清楚,请告诉我,我会尝试扩展它。

标签: c++ oop class operator-overloading friend-function


【解决方案1】:

你有

template <typename Datatype> MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);

在课堂内。它是MyClass 类的方法。非静态方法有一个称为this 指针的隐式参数。 this 指针是指向调用该方法的对象的指针。您不需要MyClassReference 参数,因为this 指针可以实现该目的。

将该方法声明更改为

template <typename Datatype> MyClass& operator<<(Datatype SomeData);

.

【讨论】:

    【解决方案2】:

    我不确定这是个好主意,但是是的 - 当您将 operator&lt;&lt; 定义为成员函数时,*this 将基本上等同于您在运算符中定义的第一个参数。

    【讨论】:

    • -1 不正确。 operator&lt;&lt; 不仅适用于流。它只是一个运算符。他正在为他的类有效地编写一个插入运算符,将Datatype 类型的对象插入到MyClass 类的对象中。
    • @Sion Sheevok:是的 - 在你发表评论之前,我就知道他在做什么并正在编辑(它只是偶然发布的)。
    【解决方案3】:

    你快到了:

    class MyClass
    {
        template <typename Datatype>
        friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData) 
        {
            // ...
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 2022-06-21
      • 2018-11-20
      • 2011-04-22
      相关资源
      最近更新 更多