多年来使用可爱的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;
}
答案 0 :(得分: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;
}