小编Cai*_*hou的帖子

为什么我们可以从函数中返回 char* ?

这是一段 C++ 代码,显示了一些非常奇特的行为。谁能告诉我为什么 strB 可以打印出这些东西?

char* strA()
{
    char str[] = "hello word";
    return str;
}

char* strB()
{
    char* str = "hello word";
    return str;
}

int main()
{ 
    cout<<strA()<<endl;  
    cout<<strB()<<endl;
}
                      
                                                                                                                                                            
Run Code Online (Sandbox Code Playgroud)

c++ scope

2
推荐指数
1
解决办法
141
查看次数

为什么这个 C++ lambda 函数返回 1?

我有一个如下的 lambda 函数,它显式声明int为它的返回类型,但在它的实现中,它什么都不做。此外,它打印出它的返回值。令我惊讶的是,它编译没有错误并返回 1。谁知道原因?

auto lambda = [](int a) -> int{};
cout << lambda << endl;
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11

1
推荐指数
1
解决办法
109
查看次数

当我通过引用传递形式参数时,为什么原始变量没有更改?

我有一个函数,该函数删除的const属性int*并更改其指向的变量的值,但是它不起作用,因为我传递了一个变量并在正式引用中对其进行了引用?

这是我的代码:

#include <bits/stdc++.h>
#include <iostream>
#include <map>
using namespace std;
typedef unsigned char UINT8;

int ll(const int &r)
{
  *(const_cast<int *>(&r)) = 5;
  // cout<<const_cast<int*> (&r)<<endl;
  //*(&r)=5;

  cout << r << endl;
}

int main()
{
  const int a = 1;

  ll(a);

  cout << a << endl;
}
Run Code Online (Sandbox Code Playgroud)

我希望函数中显示的值与中的相同main(),但有所不同。

c++

0
推荐指数
1
解决办法
56
查看次数

标签 统计

c++ ×3

c++11 ×1

lambda ×1

scope ×1