gpt4 book ai didi

C++ 运算符重载问题 : expected initializer before '<<' token

转载 作者:行者123 更新时间:2023-11-30 02:46:00 25 4
gpt4 key购买 nike

我正在尝试重载插入运算符“<<”以简化使用特定软件所需的一些语法。该软件实现了一个包含各种类型数据的哈希对象,因此无法在编译时进行类型检查,因为直到运行时才知道给定表达式的 RHS 类型。这个散列在本质上与 Boost Property Trees 非常相似。

我正在尝试将其编写为模板函数以从散列中提取数据。只要接收变量已经存在(已初始化),这就可以正常工作。如果在变量初始化期间使用它,则编译失败。

所以,这可以编译并正常工作。

int value;
value << data;

但这根本无法编译。

int value << data;

真正的代码非常庞大和复杂,所以我编写了以下简化程序来展示相同的行为。

我使用的是 gcc 4.3.4 版。不同的编译器不是一个选项。

感谢任何帮助。

#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);
}

最佳答案

int value << data;没有语法意义。

想到<<就像任何其他运营商一样,而不是像 += .是的,<<已重载,但它仍然必须遵守与其自然化身相同的语义,如按位移位。

int value += 3;例如,也没有意义。

关于C++ 运算符重载问题 : expected initializer before '<<' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23958529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com