运算符重载
#include <iostream>
using namespace std;
class A
{
int a;
public:
A(int x = 0) :a(x) {}
A operator+(const A& i)
{
return a + i.a;
}
operator int()
{
return a;
}
};
int main()
{
A a(2), b(3), c;
c = a + b;
cout << c << endl;
}
类的声明和对象的定义
1)成员数据不要改变的的定义为常成员函数
2)内联函数即可以保证程序的可读性,又能提高程序的运行效率
模板
1)
选D
自动类型转化
2)
#include<iostream>
#include<string>
using namespace std;
void Show(int x, int y) { cout << "int:" << x << "," << y << endl; }
void Show(char x, char y='a') { cout << "char:" << x << "," << y << endl; }
template<class M,class N>
void Show(M x, N y) { cout << "template:" << x << "," << y << endl; }
int main() {
string a, b;
a = "Shanghai";
b = "Hangzhou";
Show('a', 6);
Show(1, 2);
Show(a, b);
Show(65);
Show(7.2, a);
int x = 'a';
cout << x << endl;
return 0;
}
输出:
template:a,6
int:1,2
template:Shanghai,Hangzhou 即使是两个
char:A,a
template:7.2,Shanghai
97
3)
派生与继承
#include <iostream>
using namespace std;
class A {
public:
void f() { cout << "A::f()" << endl; }
};
class B {
public:
void f() { cout << "B::f()" << endl; }
void g() { cout << "B::g()" << endl; }
};
class C : public A, public B {
public:
void g() { cout << "C::g()" << endl; }
};
int main() {
C cc;
cc.B::f(); //(A)
cc.B::g(); //(B)
cc.g(); 派生类对象调用派生类的//(C)
cc.f(); 错误,两个基类都有,没有指明是哪一个的//(D)
return 0;
}