问题描述
C ++的新手,但C语言不熟悉。以前,我只是让我的函数接受对象指针,但是我试图学习C ++方式,并通过引用来处理传递的对象。
有没有一种正确的方法,可以将对象指针传递给通过引用接受对象的函数?
我举了一个示例,其中我向方法foo()
传递了取消引用的指针,但我想知道这是否被认为是C ++的良好实践,还是我应该做其他事情。
class Entity {
public:
int x;
Entity(int y) {
x = y;
}
};
void foo(Entity& e) {
std::cout << e.x << std::endl;
}
int main()
{
Entity* e = new Entity(5);
foo(*e);
}
解决方法
通过引用函数传递参数时,应将其标记为const
,以告诉自己(和其他程序员)函数不会修改传入的参数。
如果您要修改内容,则不会将其标记为const
。
class Entity {
public:
int x;
Entity(int y) {
x = y;
}
};
// pass arguments here by const reference since you're not modifying anything
void foo(const Entity& e) {
std::cout << e.x << std::endl;
}
int main() {
Entity* e = new Entity(5);
foo(*e);
}