目录
1.为什么构造函数不可以用虚函数
2.函数名字前&
这个和函数参数加地址符的作用是一样的,用于返值返回的是引用而不是赋值。
也就是说,该函数返值会通过地址传送的方式给到函数调用者要求的返回值,这样可以节省对象赋值造成的内存浪费,通常用于返值是大型对象(而不是简单变量类型)的时候。
比如你有个class T,而这个函数的返值是return T; 加上地址符返值后,返回T变量的地址,将地址传递给接收返值的变量,而不是新建一个类T,调用类的复制函数创建一个新类。
当需要改变静态成员时,需要使用引用类型的形参。
3. operator的使用
1)前置单目运算符
前++:
Point& Point::operator++() {
i++;
return *this;
}
或者
Point Point::operator++() {
i++;
return *this;
}
2)后置单目运算符
后++:
Point Point::operator++(int) {
Point old = *this;
i++;
return old;
}
3)双目运算符
传入一个参数(第二个),其他和普通函数一样
4)括号
#include <iostream>
using namespace std;
class Clastype
{
public:
Clastype(int a)
{
cout << "Hello Clastype!" << a << endl;
}
bool operator ()(int b)
{
cout << "Hello Clastype()!" << b << endl;
return true;
}
};
int main()
{
Clastype a(1);
Clastype(2);
Clastype t = Clastype(3);
t(4);
Clastype *b = new Clastype(5);
(*b)(6);
}
运行结果
Hello Clastype!1
Hello Clastype!2
Hello Clastype!3
Hello Clastype()!4
Hello Clastype!5
Hello Clastype()!6
总的代码:
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
class Point {
public:
Point(int a) { i = a; }
Point operator+(Point b) const {//双目运算符
return Point(i + b.i);
}
Point& operator++();//前置运算符
Point operator++(int);//后置运算符
void get() { cout << i << endl; }
private:
int i;
};
//前置运算符
Point& Point::operator++() {
i++;
return *this;
}
//后置运算符
Point Point::operator++(int) {
Point old = *this;
i++;
return old;
}
int main() {
Point a(3), b(5), c(0);
c = a + b;
c.get();
++c;
c.get();
c++;
c.get();
c++.get();
return 0;
}//“--”略
5)类型转换函数
http://c.biancheng.net/cpp/biancheng/view/222.html
4.输入输出
1)getchar();
以回车作为开始接受标志,读取回车,从键盘缓冲区队列中依次读取字符,读取到NULL时结束读取(函数返回NULL的acsii码值“0”)。
2)gets();
读取字符串,不读取回车,会在读取结束后在字符串末尾自动加入“\0”
3)cin
以空格、回车符等特殊字符为结束字符,会在读取结束后在字符串末尾自动加入“\0”
4)scanf
以空格为输入结束标记,会在读取结束后在字符串末尾自动加入“\0”
5)getline(cin/cout,stringname(,‘结束字符’))
默认不接受回车字符,