我可以在 C++ 中覆盖字符串 return 类型的函数吗

Can I override a string return type functions in 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. 以上代码出错。为什么我不能覆盖字符串 class.
  2. 我想用指针p调用loft()
  3. 有没有什么方法可以使用指针对象来抽象classProduct

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

loft方法没有问题,print方法有问题。 Child class 有一个 return 类型的 string 和 base class 有一个 return 类型的 void,因此你并没有真正覆盖功能。编译器在基础 class 中看到 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;
}

此外,下次请尝试更好地格式化您的代码,这样更易​​于阅读