0

谁能告诉我在主要传递给 g 时会发生什么,是 static_cast 吗?

int  & g (int&x){x++ ; return x ; } 
int main()
{

   const int a=5 ; 
   cout<<g((int&)a)<<endl; 
}

我确信没有复制,因为上面的代码类似于下面的代码:

class A
{
public:
    A()
    {
        cout << "calling DEFAULT constructor\n\n";
    }
    A(A& Other)
    {
        cout << "Calling COPY constructor\n\n";
    }
    ~A()
    {
        cout << "Calling DESTRUCTOR\n\n";
    }
};

A& g(A& x)
{
    cout << "Inside g(A& x) \n\n";
    return x;
}

void main()
{
    const A a;
    g(const_cast<A&>(a));
}*/

提前致谢 :)

4

3 回答 3

8

static_cast不能删除常量。这是一个const_cast.

在运行时,此代码(第一个示例)会产生未定义的行为,因为您修改了一个 const 对象。

于 2011-01-30T21:33:18.997 回答
1

C 风格的演员表是一种恶毒的东西——它会做 areinterpret_cast<>或 aconst_cast<>会做的所有事情。这是 C 名声在外的“电锯的力量和电锯的易用性”之一。

使用 C++ 风格的强制转换将表明您需要执行 a const_cast<>,然后您应该问自己为什么并找到更好的方法来执行此操作。

于 2011-01-30T21:36:46.117 回答
0

对于 int,不需要任何代码来传递引用。你的演员让它编译。

于 2011-01-30T21:34:41.130 回答