[英]Defining operator<< Inside Class
Consider the following code: 请考虑以下代码:
class MyClass
{
template <typename Datatype>
friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);
// ...
};
template <typename Datatype>
MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData)
{
// ...
}
How can I define operator<<
inside the class, rather than as a friend function? 我如何定义
operator<<
在类中 ,而不是作为一个友元函数? Something like this: 像这样的东西:
class MyClass
{
// ...
public:
template <typename Datatype>
MyCLass& operator<<(MyClass& MyClassReference, Datatype SomeData)
{
// ...
}
};
The above code produces compilation errors because it accepts two arguments. 上面的代码产生编译错误,因为它接受两个参数。 Removing the
MyClassReference
argument fixes the errors, but I have code that relies on that argument. 删除
MyClassReference
参数可以修复错误,但我的代码依赖于该参数。 Is MyClassReference
just the equivalent of *this
? MyClassReference
只相当于*this
吗?
You have 你有
template <typename Datatype> MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData);
inside of the class. 在课堂内。 It is a method of the class
MyClass
. 它是
MyClass
类的一种方法。 Non-static methods have an implicit parameter called the this
pointer. 非静态方法有一个名为
this
指针的隐式参数。 The this
pointer is a pointer to the object the method was called on. this
指针是指向调用该方法的对象的指针。 You do not need the MyClassReference
parameter because the this
pointer fulfills that purpose. 您不需要
MyClassReference
参数,因为this
指针实现了该目的。
Change that method declaration to 将该方法声明更改为
template <typename Datatype> MyClass& operator<<(Datatype SomeData);
. 。
我不确定这是个好主意,但是 - 当你将operator<<
定义为成员函数时, *this
基本上等同于你在运算符中定义的第一个参数。
You were almost there: 你几乎在那里:
class MyClass
{
template <typename Datatype>
friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData)
{
// ...
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.