【发布时间】:2018-07-21 04:40:26
【问题描述】:
C++
几周以来,我一直在努力学习 Inheritance 和 Polymorphism。我可以拥有带有狗和猫的哺乳动物,O 可以从 Dogs 中获得 Puppy,等等。我有一个 NaughtleNum base class 和 a + operator 而derived class 是 Naughty1。 (抱歉,我讨厌 Foo Bar)
代码如下:
#include <iostream>
#include <math.h>
using namespace std;
typedef unsigned char UCHAR;
typedef unsigned short int SHORT;
class NaughtleNum;
class Naughty1;
class NaughtleNum {
public:
NaughtleNum() {
cout << "Hello NaughtleNum 1\n";
}; //constructors
virtual~NaughtleNum() {
cout << "Bye Bye NaughtleNum\n";
}; //destructor
virtual NaughtleNum * operator + (NaughtleNum * ) = 0;
};
class Naughty1: public NaughtleNum {
public:
Naughty1() {
cout << "Hello Naughty1\n";
value = 3;
}; //constructors
~Naughty1() {
cout << "Bye Bye Naughty1\n";
}; //destructor
Naughty1 * operator + (Naughty1 * ) {}
private:
UCHAR value;
};
int main() {
cout << "I am Here\n";
NaughtleNum * N1;
N1 = new Naughty1;
return 0;
}
我想要a + operator 两个淘气号码!
消息是:
daddio@LittleBeast:~/Programs/MyLib/Naughty> g++ -g -o NaughtleNum NaughtleNum.cpp
NaughtleNum.cpp: In function ‘int main()’:
NaughtleNum.cpp:35:12: error: cannot allocate an object of abstract type ‘Naughty1’
N1=new Naughty1;
^
NaughtleNum.cpp:19:7: note: because the following virtual functions are pure within ‘Naughty1’:
class Naughty1: public NaughtleNum
^
NaughtleNum.cpp:16:30: note: virtual NaughtleNum* NaughtleNum::operator+(NaughtleNum*)
virtual NaughtleNum* operator + (NaughtleNum*) =0;
^
daddio@LittleBeast:~/Programs/MyLib/Naughty>
我在这里错过了什么?
【问题讨论】:
-
混合使用虚函数和运算符重载总是很痛苦,而且几乎没有必要。
标签: c++ inheritance polymorphism derived-class base-class