Skip to content

Commit

Permalink
增加转换函数
Browse files Browse the repository at this point in the history
  • Loading branch information
Lee committed May 3, 2018
1 parent 8e05396 commit 2dfb72e
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
chapter_8/a.out
chapter_8/carinfo.txt
chapter_9/a.out
chapter_10/a.out
19 changes: 19 additions & 0 deletions chapter_10/file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}
9 changes: 8 additions & 1 deletion chapter_10/header/file.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
18 changes: 17 additions & 1 deletion chapter_10/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}

0 comments on commit 2dfb72e

Please sign in to comment.