當使用unnamed object且須多型時,只能使用 reference,若用pointer雖可compile,但結果不正確。
以下是使用reference配合unnamed object使用多型,結果正確

1
/**//*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : Polymorphism_UnnameObject_reference.cpp
5
Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6
Description : Demo how to use reference with unnamed object
7
Release : 04/07/2007 1.0
8
*/
9
#include <iostream>
10
#include <string>
11
12
using namespace std;
13
14
class Base
{
15
protected:
16
string text;
17
18
public:
19
Base()
{}
20
Base(const char* text) : text(text)
{}
21
22
public:
23
virtual string getText()
{
24
return "Base's " + this->text;
25
}
26
};
27
28
class Derived : public Base
{
29
public:
30
Derived()
{}
31
Derived(const char *text) : Base(text)
{}
32
33
public:
34
string getText()
{
35
return "Derived's " + this->text;
36
}
37
};
38
39
int main()
{
40
Base &obj = Derived("C++");
41
cout << obj.getText() << endl;
42
}


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

27

28



29

30



31



32

33

34



35

36

37

38

39



40

41

42

執行結果

但若換成pointer,則結果錯誤
1
/**//*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : Polymorphism_UnnameObject_pointer.cpp
5
Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6
Description : Demo how to use pointer with unnamed object
7
Release : 04/07/2007 1.0
8
*/
9
#include <iostream>
10
#include <string>
11
12
using namespace std;
13
14
class Base
{
15
protected:
16
string text;
17
18
public:
19
Base()
{}
20
Base(const char* text) : text(text)
{}
21
22
public:
23
virtual string getText()
{
24
return "Base's " + this->text;
25
}
26
};
27
28
class Derived : public Base
{
29
public:
30
Derived()
{}
31
Derived(const char *text) : Base(text)
{}
32
33
public:
34
string getText()
{
35
return "Derived's " + this->text;
36
}
37
};
38
39
int main()
{
40
Base *obj = &Derived("C++");
41
cout << obj->getText() << endl;
42
}


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

27

28



29

30



31



32

33

34



35

36

37

38

39



40

41

42

執行結果

Conclusion
為什麼會如此,我並不清楚,目前只知道unnamed object若要配合多型,一定要用reference,不能用pointer,若有人知道原因請告訴我,謝謝。