在一个类里面调用别一个类的函数

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

 

 

 

 

 

 

posted @ 2013-10-15 20:54  sndnvaps  阅读(2987)  评论(0编辑  收藏  举报