如何在 VC++ 中通过引用传递另一个对象的方法(错误 C2664)
How to pass by reference to another object's method in VC++ (error C2664)
在使用可爱的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;
}
相关文章:
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 检查哪个对象调用了另一个对象的对象方法
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?
- 如何在 VC++ 中通过引用传递另一个对象的方法(错误 C2664)
- 仅将方法应用于类的一个对象
- 我是否要创建一个对象来使用C 中的类方法
- 使用方法影响另一个对象的字段
- 调用对象类方法,该方法在另一个对象类中的向量中
- 方法从C 中的另一个对象执行
- 你如何断言一个对象在c++中有一个特定的方法
- 而不是在 lua 中创建一个对象,如何让 lua 直接高C++对象来启动方法?
- C++如果我有一个对象指针,是在堆栈或堆上分配的方法变量
- 从另一个 std::thread 调用 Qt 对象方法
- 你会如何解释一个外行人或编程初学者,面向对象方法的大胆点 - 安全
- 从一个对象线程中使用 const 方法是否安全
- 如何让一个带有方法的c++对象接受封闭类的参数
- 成员函数指针指向另一个对象的方法
- 将一个对象发送到另一个对象并调用first-objects方法