如何在 VC++ 中通过引用传递另一个对象的方法(错误 C2664)

How to pass by reference to another object's method in VC++ (error C2664)

本文关键字:一个对象 方法 C2664 错误 VC++ 引用      更新时间:2023-10-16

在使用可爱的C#多年后,我的C 技能遭受了很多影响,但我有信心在您的帮助下回到正轨。通过参考类中的方法传递一个值:

// WORKS
class Foo {
  void FooAdd(int i, int j, int &k) {
    k = i + j;
  }
  void FooDo() {
    int i = 20;
    FooAdd(1, 2, i);
    std::string s = std::to_string(i) + " (3: SUCCESS; 20: ERROR)";
    std::cout << s;
  }
}
int main() {
  Foo* foo = new Foo();
  foo->FooDo();
  return 0;
}

如果此方法移至另一个类,VC 将无法再编译文件:

// error C2664: "void Bar::BarAdd(int,int,int *)" : Konvertierung von Argument 3 von "int" in "int *" nicht möglich
// error C2664: "void Bar::BarAdd(int,int,int *)" : cannot convert parameter 3 from 'int' to 'int *'
class Bar {
  void BarAdd(int i, int j, int &k) {
    k = i + j;
  }
}
class Foo {
  void FooDo() {
    int i = 20;
    Bar* bar = new Bar();
    bar->BardAdd(1, 2, i);    // error C2664
    std::string s = std::to_string(i) + " (3: SUCCESS; 20: ERROR)";
    std::cout << s;
  }
}
int main() { // unchanged
  Foo* foo = new Foo();
  foo->FooDo();
  return 0;
}

如果您纠正错字,添加缺失的半彩色,包括iostream,然后将方法公开,则可以正常工作。请参阅https://ideone.com/lwdpbl

#include <iostream>
class Bar {
public:
  void BarAdd(int i, int j, int &k) {
    k = i + j;
  }
};
class Foo {
public:
  void FooDo() {
    int i = 20;
    Bar* bar = new Bar();
    bar->BarAdd(1, 2, i);    // error C2664
    std::string s = std::to_string(i) + " (3: SUCCESS; 20: ERROR)";
    std::cout << s;
  }
};
int main() { // unchanged
  Foo* foo = new Foo();
  foo->FooDo();
  return 0;
}