有没有办法在成员函数定义中访问特定类实例的成员函数?让我在下面的伪代码中阐明我的意思。
谢谢!
// A Class called Dog
class Dog
{
public:
void eat();
void drink();
//... More code here
};
void Dog::eat()
{
//How do I always access dog1.drink() here, regardless of which instance calls it?
}
//... More code here
// Instances of Dog
Dog dog1, dog2;
最佳答案
如果你想让dog1
喝水,你只需调用:
dog1.drink();
无论你是否将其写在 Dog
的成员函数中都没有关系。这里没有必要想太多。
注意:与全局变量的任何其他使用一样,全局变量必须在使用它的代码之前声明。
关于C++如何在实例之间访问类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156005/