如果使用非 volatile 对象调用 volatile 成员函数会发生什么?
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
void func(int a) volatile //volatile function
{
x = a;
cout<<x<<endl;
}
};
int main()
{
A a1; // non volatile object
a1.func(10);
return 0;
}
最佳答案
规则与const
成员函数相同。可以在非 volatile
对象上调用 volatile
成员函数,但不能在 对象上调用非
对象。volatile
成员函数code>volatile
对于您的情况,A::func()
将被正常调用。如果相反,编译将失败。
class A
{
private:
int x;
public:
void func(int a) // non-volatile member function
{
x = a;
cout<<x<<endl;
}
};
int main()
{
volatile A a1; // volatile object
a1.func(10); // fail
return 0;
}
关于c++ - 在 C++ 中使用非 volatile 对象调用 volatile 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436071/