Chinaunix首页 | 论坛 | 博客
  • 博客访问: 513115
  • 博文数量: 158
  • 博客积分: 4015
  • 博客等级: 上校
  • 技术积分: 1711
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-27 14:00
文章分类

全部博文(158)

文章存档

2010年(71)

2009年(87)

我的朋友

分类: C/C++

2010-01-29 19:34:16

如果有两个对象:one, two, 要想把one转换成为two,有两种方法:
在one在定义operator two() const函数
在two在增加two(const one&)构造函数
一般只能使用其中一种情况,而不能两种一起使用。

operator:

#include <iostream>
using std::cout;
using std::endl;

class two {
    int iTwo;
public:
    two(int a = 0) : iTwo(a) {}
    void print() const {
        cout << "two is: " << iTwo << endl;
    }
};

class one {
    int iOne;
public:
    one(int a = 0) : iOne(a) {}
    operator two() const {
        return two(iOne);
    }
};

void f(const two& t) {
    t.print();
}

int main() {
    one o(143);
    f(o);
}

构造函数转换:

#include <iostream>
using std::cout;
using std::endl;
class one {
    int iOne;
public:
    one(int a = 0) : iOne(a) {}
    int getValue() const {
        return iOne;
    }

};

class two {
    int iTwo;
public:
    two(int a = 0) : iTwo(a) {}
    two(const one& o) {
        iTwo = o.getValue();
    }
    void print() const {
        cout << "two is :" << iTwo << endl;
    }
};

void f(const two& t) {
    t.print();
}

int main() {
    one one(222);
    f(one);
}


阅读(1427) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~