【发布时间】:2016-06-26 12:15:24
【问题描述】:
我不明白为什么这不能编译:
#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;
}
- 上述代码导致错误。为什么我不能覆盖字符串类。
- 我想使用指针
p调用loft()。 - 有没有办法使用指向抽象类
Product的指针对象来实现这一点
【问题讨论】:
-
您不会覆盖
std::string。请修正您的术语。请显示您在代码中遇到的逐字错误。 -
请下次,让你的代码更具可读性。从长远来看,这对你来说也会更顺利:)
-
我会开始查看
line 30:7: error: virtual function 'slog' has a different return type ('int') than the function it overrides (which has return type 'void') int slog() { ...并从顶部开始解决错误(通常更有意义,修复第一个错误,然后重新运行,因为“后续错误”的光学噪音来自一个最初的,没有生产力。如果有什么不可修复的,只需复制上述问题中的剩余错误,看看人们是否可以提供进一步的帮助。谢谢。
标签: c++ string stl overriding