静态成员函数调用

本文展示了一个使用 C++ 编写的简单示例程序,通过定义一个包含静态成员变量和方法的类来跟踪对象的创建数量。该程序演示了如何初始化静态成员变量,并展示了如何使用静态成员函数来更新静态变量。

#include<iostream.h>
class teach
{private:
 static int counter;
 int id;
public:
 teach();
     void show();
  static void setcounter(int);
  };
  int teach::counter=1;//静态数据成员初始化
  teach::teach()
  {id=counter++;;
  }
  void teach::show()
  {cout<<id<<endl;
  }
  void teach::setcounter(int new_counter)
  {counter=new_counter;
  }
 int main()
  {teach s1;
  s1.show();
  teach s2;
  s2.show();
  teach s3;
  s3.show();
  s1.setcounter(10);//重新设置计数器
  teach s4;
  s4.show();
  teach s5;
  s5.show();
  return 0;
  }
    

 

 

### 静态成员函数与非静态成员函数的调用方式差异 在 C++ 中,静态成员函数和非静态成员函数是类中两种不同的成员函数类型,它们的调用方式存在显著差异。以下是两者的调用方式及其特点的详细对比: #### 1. 调用方式 - **静态成员函数** 静态成员函数属于类本身,而不属于某个具体的对象实例。因此,它可以使用类名直接调用,而无需创建类的对象实例。例如: ```cpp class MyClass { public: static void staticFunction() { // 静态成员函数实现 } }; MyClass::staticFunction(); // 使用类名直接调用静态成员函数[^1] ``` - **非静态成员函数** 非静态成员函数属于类的具体对象实例,必须通过对象实例来调用。这是因为非静态成员函数需要访问 `this` 指针,而 `this` 指针指向的是调用该函数的具体对象实例。例如: ```cpp class MyClass { public: void nonStaticFunction() { // 非静态成员函数实现 } }; MyClass obj; obj.nonStaticFunction(); // 必须通过对象实例调用非静态成员函数[^2] ``` #### 2. 对象依赖性 - **静态成员函数** 静态成员函数不依赖于任何对象实例,因此它无法访问非静态成员变量或非静态成员函数。这是由于静态成员函数没有隐式的 `this` 指针,也就无法引用具体对象的成员。例如: ```cpp class MyClass { private: int x; public: static void staticFunction() { // 不能访问 x 或非静态成员函数 } }; ``` - **非静态成员函数** 非静态成员函数依赖于具体的对象实例,可以通过 `this` 指针访问对象的非静态成员变量和其他非静态成员函数。例如: ```cpp class MyClass { private: int x; public: void nonStaticFunction() { x = 10; // 可以访问非静态成员变量 x } }; ``` #### 3. 相互调用限制 - **静态成员函数调用静态成员函数** 静态成员函数无法直接调用非静态成员函数,因为静态成员函数没有 `this` 指针,无法确定调用哪个对象的非静态成员函数。如果需要调用非静态成员函数,则必须显式传递一个对象指针或引用。例如: ```cpp class MyClass { public: void nonStaticFunction() {} static void staticFunction(MyClass& obj) { obj.nonStaticFunction(); // 显式通过对象调用非静态成员函数[^2] } }; ``` - **非静态成员函数调用静态成员函数** 非静态成员函数可以直接调用静态成员函数,因为它可以通过类名访问静态成员函数,无需依赖 `this` 指针。例如: ```cpp class MyClass { public: static void staticFunction() {} void nonStaticFunction() { staticFunction(); // 直接调用静态成员函数[^3] } }; ``` ### 示例代码 以下是一个综合示例,展示了静态成员函数和非静态成员函数的调用方式及相互调用的实现: ```cpp #include <iostream> using namespace std; class MyClass { private: int x; public: static void staticFunction() { cout << "This is a static function." << endl; } void nonStaticFunction() { cout << "This is a non-static function." << endl; staticFunction(); // 非静态成员函数调用静态成员函数 } static void callNonStaticFunction(MyClass& obj) { obj.nonStaticFunction(); // 静态成员函数通过对象调用非静态成员函数 } }; int main() { MyClass::staticFunction(); // 使用类名调用静态成员函数 MyClass obj; obj.nonStaticFunction(); // 使用对象调用非静态成员函数 MyClass::callNonStaticFunction(obj); // 静态成员函数调用静态成员函数 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值