关于语法
  • 板块学术版
  • 楼主yukimianyan
  • 当前回复5
  • 已保存回复5
  • 发布时间2023/12/15 18:21
  • 上次更新2023/12/15 20:11:13
查看原帖
关于语法
509229
yukimianyan楼主2023/12/15 18:21

现在有这么一段代码,定义了类型 node,void node::add() 是一个成员函数。定义了两个 node 类型的变量 a, b,希望使用如下代码使得他们都执行 .add() 方法:


#include <bits/stdc++.h>
using namespace std;
struct node {
  int x;
  void add() { ++x; }
};
int main() {
  node a = {1}, b = {2};
  cout << a.x << " " << b.x << endl;
  for (auto& x : {a, b}) x.add();
  cout << a.x << " " << b.x << endl;
  return 0;
}

期望输出 1 2 和 2 3,但是 编译错误:

test.cpp: In function ‘int main()’:
test.cpp:20:31: error: passing ‘const node’ as ‘this’ argument discards qualifiers [-fpermissive]
   20 |   for (auto& x : {a, b}) x.add();
      |                          ~~~~~^~
test.cpp:12:8: note:   in call to ‘void node::add()’
   12 |   void add() { ++x; }
      |        ^~~

将 auto &x 的 & 去掉,则编译通过,输出 1 2 和 1 2,不符合预期。

求一种方法使得可以通过编译并输出期望结果。

2023/12/15 18:21
加载中...