zoukankan      html  css  js  c++  java
  • 在一个类里面调用别一个类的函数

    sample:

    //part A
    //tmp.hpp
    #ifndef TEMP_HPP
    #define TEMP_HPP
    
    class tmp {
          public:
                  void print();
           private:
                   std::string str2;
    };
    
    #endif
    // part B
    //tmp.cpp
    #include <iostream>
    #include "tmp.hpp"
    
    #include "test.hpp"
    
    using namespace std;
    void tmp::print() {
        str2 = " this is the tmp print func";
        cout << str2 << endl;
    
        test::show();
    }
    
    int main() {
    
        tmp temp;
        temp.print();
        return 0;
    }
    //part C
    //test.hpp 
    #ifndef TEST_HPP
    #define TEST_HPP
    #include <iostream>
    using namespace std;
    class test {
        test();
        ~test();
        public:
        static void show();
    
        //private:
    //    string str;
    };
    
    #endif
    //part D
    //test.cpp 
    #include <iostream>
    
    #include "test.hpp"
    using namespace std;
    test::test() {
    //    str = "this is test";
    }
    
    test::~test() {
    }
    
    void test::show() {
        string str = "this is test func";
        cout << str << endl;
    }

    为了能在tmp::print()调用test::show()函数

    需要在tmp.cpp中调用 "test.hpp"

    且test::show()的定义必须为 static;

    编译命令:

    gcc -o main tmp.cpp test.cpp 


    运行结果如下:

    $ ./main
     this is the tmp print func
    this is test func
  • 相关阅读:
    PHP自动加载(__autoload和spl_autoload_register)
    抽象工厂模式
    工厂方法模式
    简单工厂模式
    组合
    二叉树的层次遍历 II
    umask命令
    二叉树的所有路径
    CDN缓存的理解
    Js中RegExp对象
  • 原文地址:https://www.cnblogs.com/sn-dnv-aps/p/3370981.html
Copyright © 2011-2022 走看看