我的CPP之路

路漫漫其修远兮
随笔 - 42, 文章 - 0, 评论 - 16, 引用 - 0
数据加载中……

重载运算符小记_1

今天试验了重载运算符,笔记一下,编程过程中也发现,new返回的是一个指针,需要注意。

 1#include <iostream>
 2
 3class RevOp {
 4public:
 5    RevOp();
 6    RevOp(int);
 7    int getVal() const//如果下面一行的参数中加const,这行const不加的话,则会出现第34行的错误。
 8    RevOp operator + (const RevOp&);
 9private:
10    int val;
11}
;
12
13int main() {
14    //RevOp R1 = new R1(1); //此行错!new返回的是一个指针!类型是void *!
15    RevOp R1(1), R2(2), R3;
16    std::cout << R3.getVal() << std::endl;
17    R3 = R1 + R2;
18    std::cout << R3.getVal() << std::endl;
19
20    return 0;
21}

22
23RevOp::RevOp():val(0{
24}

25
26RevOp::RevOp(int x):val(x) {
27}

28
29int RevOp::getVal() const {
30    return this->val;
31}

32
33RevOp RevOp::operator + (const RevOp& X) {
34    return RevOp(val - X.getVal()); // passing `const RevOp' as `this' argument of `int RevOp::getVal()' discards qualifiers
35}

36

在gcc 3.4.5下编译通过,最后把+重载成了-,呵呵,试验成功。
以后密切注意const到底用不用好,到底是用指针合适还是引用合适。不过还好,客户要我用什么,我就能用什么。

posted on 2008-04-17 19:20 yanvenhom 阅读(325) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理