C++如何在实例之间访问类成员函数

标签 c++ class

有没有办法在成员函数定义中访问特定类实例的成员函数?让我在下面的伪代码中阐明我的意思。

谢谢!

// 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/

相关文章:

c++ - 如何解决 "must specify at least one argument for ' .. .' parameter of variadic macro"

c++ - 将参数转发给 lambda 以供后续异步调用

c++ - GTK 应用程序 : How do I create a working indicator with Qt/C++?

c++ - 使用 boost::serialization 序列化递归图结构时如何防止堆栈溢出?

java - 如何作为类成员从数组中获取长度?

c++ - 字符串 Vector push_back 在类里面失败

c++ - 如何从 Alexandrescu A. 'Append' 编译模板类 "Modern C++ Design. Generic Programming and Design Patterns Applied"?

c++为相同类型专门化类行为

scala - scala中的对象实例化变体

ruby-on-rails - 为什么 Rails 模型中的新类方法结果为零?