C++ 杂项

1. 操作符重载

定义:
// Time.h
class Time {
  ...
  public:
      ...
      Time operator+ (const Time &t) const;
      ...  
};
实现
// Time.cpp
...
Time Time::operator+ (const Time &t) const
{
   Time sum;
   sum.minutes = minutes + t.minutes;
   sum.hours = hours + t.hours + sum.minutes / 60;
   sum.minutes %= 60;
   return sum; 
}
...

2. <<的重载

问题:

传统的 cout << "";  接受的是字符串,如果我们需要他能够输出一个类。这里需要用到友元和操作符的重载。

如果像上面使用类成员操作符的重载,则类必须放在第一个参数中,最后调用会是这样的

$ Time << cout

这样就有点迷惑性了,为了显示正常的样式,可以使用友元来做。

// Time.h
class Time {
    ...
    friend void operator<< (ostream &os, const Time &t);
};

// Time.cpp
...
void operator<< (ostream &os, const Time &t) {
    os << t.hours << " hours, " << t.minutes << " minutes.";
}

int main() {
    Time t(2, 30);
    cout << t;
}

// 输出
2 hours, 30 minutes.

但是如果<<符使用多个,则上面的代码会报错。修改如下

// Time.h
class Time {
    ...
    friend Time & operator<< (ostream &os, const Time &t);
};

// Time.cpp
...
ostream & operator<< (ostream &os, const Time &t) {
    os << t.hours << " hours, " << t.minutes << " minutes.";
    return os;
}

3. 虚函数

类的构造函数不能是虚函数,因为都要执行。类的析构函数应该是虚函数,why?

4. 工程文件  ProjName.dsp

我们在写工程的时候,需要向工程中添加文件 .cpp, .h,这时如果使用IDE工具如 VC,工具会自动向工程的 dsp 文件中添加我们新加文件的信息。

SOURCE=.\DlgXysxZy.cpp
# End Source File
# Begin Source File

SOURCE=.\DlgXysxZy.h
# End Source File
# Begin Source File

这里可以看到工程中就有这2个文件了,注意后面的 # 内容,这不是注释,感觉像是一种格式。  如果删掉 # 的内容,编译的时候会报错,提示加入的文件没有找到,即文件没有正确的加入到工程中。

5. MFC中的CString和类

class CommParam {
  CString add1;
  CString add2;
};

CommParam commParam;

定义上面的这个类,其内存表现为:

commParam的内存中存放的是add1, add2这2个类的地址,所以大小为8字节。

190153_Sifs_1580806.png

190259_EvpP_1580806.png

转载于:https://my.oschina.net/kuangcaibao/blog/397533

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值