C++ C++;运算符重载问题:在'<<';代币
我试图重载插入操作符'代码> int值 <代码> int值,这只是无效的C++语法。运算符重载允许您添加新语义,但不能添加新语法。C++ C++;运算符重载问题:在'<<';代币,c++,templates,compiler-construction,initializer,C++,Templates,Compiler Construction,Initializer,我试图重载插入操作符'代码> int值 int值,这只是无效的C++语法。运算符重载允许您添加新语义,但不能添加新语法。 int value; value << data; int value << data; #include <iostream> /** * Simple class to use with the templates. */ class Data { public: Data () {
int value;
value << data;
int value << data;
#include <iostream>
/**
* Simple class to use with the templates.
*/
class Data
{
public:
Data ()
{
m_value = 0;
}
Data (int val)
{
m_value = val;
}
~Data ()
{
}
int value ()
{
return (m_value);
}
int value (int val)
{
m_value = val;
return (value ());
}
private:
int m_value;
};
/**
* Assign data from RHS to LHS.
*/
template <class T>
void operator<< (T &data, Data &node)
{
data = node.value ();
}
/**
* Simple test program.
*/
int main (int argc, char *argv[])
{
// initialize the data
Data data (123);
std::cout << data.value () << std::endl;
// extract the data and assign to integer AFTER initialization
int value;
value << data;
std::cout << value << std::endl;
// extract the data and assign to integer DURING initialization
// *** problem is here ***
int other << data; // <-- this fails to compile with...
// expected initializer before '<<' token
std::cout << other << std::endl;
return (0);
}