zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++之嵌套内部类用法(七十五)

C++ 用法 内部 嵌套
2023-09-14 09:09:57 时间

1.代码示例 

1.test.h
#include <iostream>
using namespace std;

//父类
class Person{
public:
  int num;
  void foo();
  
  //静态变量
  static string mSelf;
  static int add(int x, int y);
  
  //内部类
  class Student{
  public:
    int num;
    void foo();
    static string mSelf;
    static int add(int x, int y);
 
  } stu;
};

2.test.cpp
#include "inner.h"

void Person::foo(){
  num = 11111;
  cout << " Parent Class method..." << endl;
}
void Person::Student::foo(){
  num = 22222;
  cout << " Son Class method..." << endl;
}


//错误用法
#if 0
static int Person::add(int x, int y){  
  cout <<__FUNCTION__<<"(), line = " <<__LINE__<<", x + y = " << x + y << endl;
}

static int Person::Student::add(int x, int y){
  cout <<__FUNCTION__<<"(), line = " <<__LINE__<<", x + y = " << x + y << endl;
}
#endif

//正确用法
int Person::add(int x, int y){  
  cout <<__FUNCTION__<<"(), line = " <<__LINE__<<", x + y = " << x + y << endl;
}

int Person::Student::add(int x, int y){
  cout <<__FUNCTION__<<"(), line = " <<__LINE__<<", x + y = " << x + y << endl;
}

//错误用法
//static string Person::mSelf = "I in Person Class";
//static string Person::Student::mSelf = "I in Son Class";

//正确用法
string Person::mSelf = "I in Person Class";
string Person::Student::mSelf = "I in Son Class";

int main()
{
  Person per;
  Person *ppp = new Person;
  per.foo();
  ppp->add(111, 111);
  Person::add(123,456);
  cout << Person::mSelf << endl;
  cout << per.num << endl << endl;

  cout << "**************************************" << endl;
  per.stu.foo();
  per.stu.add(1,2);
  Person::Student::add(2222,33333);
  cout << Person::Student::mSelf << endl;
  cout << per.stu.num << endl;
  return 0;
}