class A { ... virtual int fun(); void fun(int); void fun(double, double); static int fun(char); ... };
class A { public: virtual void fun(int) { } }; class B: public A { public: void fun(int) { } };
class A { public: void fun(int) { } }; class B: public A { public: void fun(int) { } //隐藏父类的fun函数 };
B b; b.fun(2);
B b; b.A::fun(2);
class A { public: virtual void fun(int) { } }; class B: public A { public: void fun(char) { } //隐藏父类的fun函数 };
B b; b.fun(2);
B b; b.A::fun(2);
class A { public: A() {cout << "construct A" << endl;} ~A() {cout << "destroy A" << endl;} }; class B: public A { public: B() {cout << "construct B" << endl;} ~B() {cout << "destroy B" << endl;} }; void main() { B obj; }
A *pa = new A[10]; delete []pa;
必须是成员函数,不能是友元函数
没有参数
不能指定返回类型
函数原型:operator 类型名();
#include <iostream> using namespace std; class Integer { public: Integer(int n); ~Integer(); Integer &operator++(); Integer operator++(int n); operator int(); void Display() const; private: int n_; }; Integer::Integer(int n) : n_(n) { } Integer::~Integer() { } Integer &Integer::operator ++() { ++n_; return *this; } Integer Integer::operator++(int n) { Integer tmp(n_); n_++; return tmp; } Integer::operator int() { return n_; } void Integer::Display() const { cout << n_ << endl; } int add(int a, int b) { return a + b; } int main(void) { Integer n(100); n = 200; n.Display(); int sum = add(n, 100); cout << sum << endl; int x = n; int y = static_cast<int>(n); return 0; }
运行结果:
200
300
解释:其中n = 200; 是隐式将int 转换成Interger类;int x = n; 是调用operator int 将Interger 类转换成int,也可以使用static_cast 办到;此外add 函数传参时也会调用operator int 进行转换。
(1)C++中“->“与“.“的区别
->是指针指向其成员的运算符 .是结构体的成员运算符
struct A { int a; int b; }; A *point = malloc(sizeof(struct A)); point->a = 1; A object; object.a = 1;
(2)类* operator->(); 与 类& operator*();
#include <iostream> using namespace std; class DBHelper { public: DBHelper() { cout << "DB ..." << endl; } ~DBHelper() { cout << "~DB ..." << endl; } void Open() { cout << "Open ..." << endl; } void Close() { cout << "Close ..." << endl; } void Query() { cout << "Query ..." << endl; } }; class DB { public: DB() { db_ = new DBHelper; } ~DB() { delete db_; } DBHelper *operator->() { return db_; } DBHelper &operator*() { return *db_; } private: DBHelper *db_; }; int main(void) { DB db; db->Open(); db->Query(); db->Close(); (*db).Open(); (*db).Query(); (*db).Close(); return 0; }
解释:db->Open(); 等价于 (db.operator->())->Open(); 会调用operator-> 返回DBHelper类的指针,调用DBHelper的成员函数Open()。这样使用的好处是不需要知道db 对象什么时候需要释放,当生存期结束时,会调用DB类的析构函数,里面delete db_; 故也会调用DBHelper类的析构函数。
(*db).Open(); 等价于(db.operator*()).Open();
参考:
C++ primer 第四版
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++ Primer 学习笔记_28_操作符重载与转换(3)--成员函数的重载、覆盖与隐藏、类型转换运算符、*运算符重载、->运算符重载
原文地址:http://blog.csdn.net/keyyuanxin/article/details/47321715