在C++中使用非volatile对象调用volatile成员函数

msc*_*msc 5 c++ volatile member-functions c++11

如果使用非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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 7

规则与const成员函数相同.甲volatile成员函数可以被称为非对volatile对象,但非volatile成员函数无法一个上被调用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;
}
Run Code Online (Sandbox Code Playgroud)