使用指针通过引用调用

py3*_*300 1 c++ pointers

我对 C++ 很陌生,而且我刚刚开始使用指针,因此当我使用指针进行引用调用时,当我传递值的地址时我无法理解一件事,它应该按应有的方式工作

void swap(int* a, int* b) {
    int temp = *a;
   *a = *b;
   *b = temp;
}

int main(){
    int x=5 , y=10;
    swap(&x , &y);
    std::cout<<"The value of x is "<<x<<std::endl;
    std::cout<<"The value of y is "<<y<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是当我传递值而不是地址时,它仍然如何工作?

int main(){
    int x=5 , y=10;
    swap(x , y);
    std::cout<<"The value of x is "<<x<<std::endl;
    std::cout<<"The value of y is "<<y<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*nny 5

这不应该编译,你不能将 an 传递int给 an int*。可能发生的情况是,你有一个

using namespace std;
Run Code Online (Sandbox Code Playgroud)

声明在开始,并且swap(x, y)实际上是在调用std::swap. 去掉 using 语句,它应该正确地无法编译。


使用命名空间会带来许多陷阱,请阅读为什么“使用命名空间 std;”来了解更多相关信息。被认为是不好的做法?