gpt4 book ai didi

c++ - 没有已知的参数 1 从 'Traffic_light' 到 'Traffic_light&' 的转换

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:43 24 4
gpt4 key购买 nike

我正在尝试“The C++ Programming Language”一书中的示例。并且有一个 enum 运算符定义的例子。

#include <iostream>

using namespace std;

enum Traffic_light {
green,
yellow,
red
};

Traffic_light& operator++(Traffic_light& t)
{
switch(t) {
case Traffic_light::green: return t=Traffic_light::yellow;
case Traffic_light::yellow: return t=Traffic_light::red;
case Traffic_light::red: return t=Traffic_light::green;
};
};

int main()
{
Traffic_light next = ++Traffic_light::yellow;
return 0;
}

但是当我尝试编译它时出现错误

main.cpp: In function 'int main()':
main.cpp:22:23: error: no match for 'operator++' (operand type is 'Traffic_light')
Traffic_light next = ++Traffic_light::yellow;
^
main.cpp:22:23: note: candidate is:
main.cpp:11:16: note: Traffic_light& operator++(Traffic_light&)
Traffic_light& operator++(Traffic_light& t)
^
main.cpp:11:16: note: no known conversion for argument 1 from 'Traffic_light' to 'Traffic_light&'

我在cmd中使用这个命令编译它

g++ main.cpp -o main.exe --std=c++11

有什么问题?

最佳答案

你应该坚持 operator++ 的通用实现,即

// preincrementation
Enum& operator++( Enum &c ) {
// do incrementation logic
return *this;
}

// postincrementation
Enum operator++( Enum &e, int ) {
Enum old = e; // copy old state
++e; // increment in therms of preincrement
return old;
}

但由于您想临时调用预增量运算符,即

Traffic_light next = ++Traffic_light::yellow;

那么你必须偏离这个模式,你可能想这样写 operator++:

#include <iostream>

enum Traffic_light { green, yellow, red, END};

Traffic_light operator++( Traffic_light t)
{
// increment
t = static_cast< Traffic_light>( static_cast<int>(t) + 1 );

// wrap if out of range
if ( t == Traffic_light::END )
t = static_cast< Traffic_light> (0);

return t;
};

Traffic_light operator++( Traffic_light l, int)
{
Traffic_light t = l;
++l;
return t;
};

int main()
{
Traffic_light nextPre = ++Traffic_light::yellow;
std::cout << nextPre; // prints 1

Traffic_light nextPost = Traffic_light::yellow++;
std::cout << nextPost; // prints 2

return 0;
}

http://ideone.com/Ixm7ax

关于c++ - 没有已知的参数 1 从 'Traffic_light' 到 'Traffic_light&' 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27691196/

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