虚函数与继承,转换函数

虚函数与继承

1
2
3
4
5
6
7
8
class shape
{
public:
virtual void draw() const = 0; //pure virtual,一定要定义
virtual void error(const std::string& msg);
//impure virtual,希望重新定义,而且已有默认定义
int objectID() const; //non-virtual,不希望重新定义
}

转换函数

情况1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Fraction
{
public:
Fraction(int num, int den = 1)
: m_numerator(num), m_denominator(den) { } //(1)
operator double() const //转换函数
{
return (double)(m_numerator / m_denominator);
}
private:
int m_numerator; //分子
int m_denominator; //分母
};


Fraction f(3, 5); //调用(1)
double d = 4 + f; //调用operator double将f转为0

情况2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Fraction
{
public:
Fraction(int num, int den = 1)
: m_numerator(num), m_denominator(den) { }
/*
non-explicit-one-argument ctor
explicit:可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生。
声明为explicit的构造函数,能在隐式转换中使用
one-argument:因为den有默认值,所以此处指的是只需要一个参数的值就够了
*/
Fraction operator+ (const Fraction& f)
{
return Fraction(...);
}
private:
int m_numerator; //分子
int m_denominator; //分母
};


Fraction f(3, 5);
Fraction d2 = f + 4;
//调用non-explicit ctor将4转化为Fraction(4, 1),然后调用operator+

情况3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Fraction
{
public:
Fraction(int num, int den = 1)
: m_numerator(num), m_denominator(den) { } //(1)
operator double() const
{
return (double)(m_numerator / m_denominator);
}
Fraction operator+ (const Fraction& f)
{
return Fraction(...);
}
private:
int m_numerator; //分子
int m_denominator; //分母
};


Fraction f(3, 5); //调用(1)
Fraction d = f + 4; //error, ambiguous
/*
此情况下,编译器可以按照情况2将4转化为Fraction,即1/4
也可以按照情况1将f转化为0.6(3/5的结果)
此时就会互相矛盾,出现error
*/

情况4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Fraction
{
public:
explicit Fraction(int num, int den = 1)
: m_numerator(num), m_denominator(den) { } //(1)
operator double() const
{
return (double)(m_numerator / m_denominator);
}
Fraction operator+ (const Fraction& f)
{
return Fraction(...);
}
private:
int m_numerator; //分子
int m_denominator; //分母
};


Fraction f(3, 5);
Fraction d = f + 4; //error:conversion from 'double' to 'Fraction' request
/*
不能调用(1)将4变化Franction类型,同时重载了+法是Fraction类型相加,所以会失败
*/