[英]Cannot change value of volatile variable
Description: 描述:
I cannot set a variable or change it while it is defined volatile (in Main). 我无法设置变量或在定义volatile时更改它(在Main中)。 Removing volatile solves the problem, but I need my variable to be volatile.
删除volatile解决了这个问题,但我需要变量是volatile。
My tries: 我的尝试:
Really a lot of tries out there. 真的很多尝试在那里。 Overloading operator=, making new operator= volatile, making new volatile method.
重载operator =,使new operator = volatile,制作新的volatile方法。 Nothing actually worked so far.
迄今为止没有任何实际工作。
My main: 我的主要:
int main() {
volatile PlaceParentConversion s(10.0); // remove volatile = no errors
std::cout << s.mX << std::endl;
s = PlaceParentConversion::IDENTITY_CONVERSION;
std::cout << s.mX << std::endl;
return 0;
}
My class: 我的课:
class PlaceParentConversion {
public: //all public, easier to check
const static PlaceParentConversion IDENTITY_CONVERSION;
double mX;
PlaceParentConversion(const double x);
PlaceParentConversion(const PlaceParentConversion& other);
};
const PlaceParentConversion PlaceParentConversion::IDENTITY_CONVERSION(0);
PlaceParentConversion::PlaceParentConversion(const double x) : mX(x) {}
PlaceParentConversion::PlaceParentConversion(const PlaceParentConversion& other) : mX(other.mX) {}
Error: 错误:
‘volatile PlaceParentConversion’ as ‘this’ argument of ‘PlaceParentConversion& PlaceParentConversion::operator=(const PlaceParentConversion&)’ discards qualifiers [-fpermissive]
Define a volatile
assignment operator: 定义
volatile
赋值运算符:
Foo volatile & operator=(Foo const & rhs) volatile
{
// ...
return *this;
}
(I've shortened your class name for readability.) (为了便于阅读,我缩短了你的班级名称。)
Here's a more complete example: 这是一个更完整的例子:
struct Foo
{
Foo() { }
Foo(Foo const volatile &) { }
Foo volatile & operator=(Foo const &) volatile
{ return *this; }
};
int main()
{
volatile Foo x;
Foo y;
static_cast<Foo>(x = y);
}
The static cast in the final line makes GCC not issue a warning that no access is happening to the volatile object which is the result of the evaluation of the assignment expression: the standard says that in a void context there is no lvalue-to-rvalue conversion and thus no access. 最后一行中的静态强制转换使得GCC不会发出警告,表明不会对volatile对象进行访问,这是对赋值表达式求值的结果:标准说在void上下文中没有左值到右值转换,因此无法访问。 We make the conversion explicit.
我们明确转换。
是的,这是正确的,因为你没有volatile PlaceParentConversion& operator =(const PlaceParentConversion&) volatile;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.