diff --git a/.gitignore b/.gitignore index 06bbed7..352a38a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ chapter_8/a.out chapter_8/carinfo.txt chapter_9/a.out +chapter_10/a.out diff --git a/chapter_10/file.cpp b/chapter_10/file.cpp index 0b7bdff..b0f86f3 100755 --- a/chapter_10/file.cpp +++ b/chapter_10/file.cpp @@ -88,3 +88,22 @@ std::ostream & operator<<(std::ostream & os, const Stock & s) << "_b: " << s._b << endl << endl; return os; } + +Stock::operator int () const +{ + cout << "operator int () const\n"; + return 1; +} + +Stock::operator double () const +{ + cout << "operator double () const\n"; + return 2.0; +} + + +Stock::operator char () const +{ + cout << "operator char () const\n"; + return 'h'; +} diff --git a/chapter_10/header/file.h b/chapter_10/header/file.h index 0f2e82d..8ea0755 100644 --- a/chapter_10/header/file.h +++ b/chapter_10/header/file.h @@ -20,16 +20,23 @@ class Stock public: Stock(); Stock(double n); - explicit Stock(int n); + explicit Stock(int n); //显示初始化 Stock(const std::string & co, double a1 = 1, double b1 = 0); ~Stock(); + void show(void) const; //当定义常量的类时,可以调用该方法 const Stock & topval(const Stock & s) const; + Stock operator+(const Stock & s) const; //重载加法 Stock operator*(double m) const; //重载乘法 + friend Stock operator*(double m, const Stock & n); //重载超过一个参数,则只能写成友元函数 friend std::ostream & operator<<(std::ostream & os, const Stock & s); + + operator int () const; //转换函数 + operator double () const; + explicit operator char () const; }; #endif \ No newline at end of file diff --git a/chapter_10/main.cpp b/chapter_10/main.cpp index 480201d..1c28caf 100755 --- a/chapter_10/main.cpp +++ b/chapter_10/main.cpp @@ -18,13 +18,17 @@ void class_test(void); void class_this_test(void); void class_operator_test(void); void friend_test(void); +void convert_function_test(void); + int main(int agrs, char *argv[]) { - class_test(); + // class_test(); // class_this_test(); //class_operator_test(); //friend_test(); + convert_function_test(); + cin.get(); cin.get(); @@ -132,4 +136,16 @@ void friend_test(void) } } +//转换函数,将类对象赋值给其他类型 +void convert_function_test(void) +{ + Stock stock1("Lee", 1, 1); + int a = stock1; + double b = stock1; + + // long c = stock1; //有二意性,编译报错 + long d = (int) stock1; //指定转换函数 + // char e = stock1; //explicit声明,必须加显示使用显示转换 + char e = (char)stock1; +} \ No newline at end of file