我无法理解为什么不编译:
#include<iostream>
#include<string>
using namespace std;
class Product {
public:
virtual void print() = 0;
virtual void slog() = 0;
virtual void loft() = 0;
};
class Bike: public Product {
private:
string s;
public:
Bike(string x){
s = x;
}
void print() {
std::cout << "Bike";
}
int slog() {
return 4;
}
string loft() {
return s;
}
};
int main() {
string s("Hello");
Product *p = new Bike(s);
p->print(); //works fine
cout << p->slog();//works fine
cout << p->loft(); //error
return 0;
}
loft()
来调用p
。Product
答案 0 :(得分:3)
首先,您需要包含字符串#include <string>
。
答案 1 :(得分:1)
loft
方法没问题,您遇到print
方法问题。 Child类的返回类型为string
,基类的返回类型为void
,因此您并未真正覆盖该函数。编译器会在基类中看到void print()
的声明,而您无法对其进行cout
。
这是您的代码,几乎没有修复和评论,它应该可以正常工作。
#include <iostream>
#include <string>
using namespace std;
class Product {
public:
virtual void print() = 0;
virtual int slog() = 0;
virtual string loft() = 0;
//added virtual destructor so you can use pointer to base class for child classes correctly
virtual ~Product() {};
};
class Bike: public Product {
string s;
public:
Bike(string x) {
s = x;
}
void print() {
cout << "Bike";
}
int slog() {
return 4;
}
string loft() {
return s;
}
};
int main() {
string s("Hello");
Product *p = new Bike(s);
p->print();
cout << p->slog();
cout << p->loft();
return 0;
}
另外,请尝试下次更好地格式化代码,以便于阅读