完美的C++面向对象之友元类,静态成员函数

今天心血来潮想写一些友元函数的test,一直我都感觉c++的面向对象是最容易理解的,感觉很贴近生活,真的是对现实世界对象的抽象,不亏是B什么大师的设计阿。

 这个例子展示到c++这几点 用法,构造函数初始化列表,类静态函数,友元类,都是在基本上俩年没碰c++后凭感觉写的,可见一旦体会到之后,c++的对象并没有那么难理解的。下面是例子

 

#include <iostream>
using
 namespace std;

class TestA
{
        friend 
class TestB;

        
private:
                
int i;

        
public:
                TestA() : i(
1024)
                {

                }

                
~TestA()
                {
                        cout 
<< "the value is " << this-><< endl;
                }

};

class TestB
{
        
public:
                
static void getFromFriend(const TestA *);
};

void TestB::getFromFriend(const TestA *obj)
{
        cout 
<< "the private member of my friend is " << obj-><< endl;
}

int main() {
        TestA obj;
        TestB::getFromFriend(
&obj);

        
return 0;
}


 把它存为test.cpp

然后用gcc编译链接

 g++ test.cpp -o test

运行

./test

 

输出为:

the private member of my friend is 1024

the value is 1024

 这很容易理解,因为创建在stack中的对象,在退出作用域时会销毁,这个时候才调用析构函数

从后the value is 1024输出在后面。

posted on 2010-01-27 23:02  eleganthqy  阅读(533)  评论(0编辑  收藏  举报

导航