我可以在c++中重写字符串返回类型函数吗?



我不明白为什么这不能编译:

#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; 
}
  1. 上面的代码导致错误。为什么我不能重写字符串类。
  2. 我想用指针p来调用loft()
  3. 是否有任何方法来实现这使用指针对象抽象类Product

首先,您需要包含字符串#include <string>

loft方法没有问题,print方法有问题。子类的返回类型为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;
}

另外,下次请尝试更好地格式化你的代码,它使它更容易阅读

最新更新