"cout"未命名类型错误

"cout" does not name a type error

本文关键字:错误 类型 未命名 cout      更新时间:2023-10-16

我正在尝试纯虚拟功能。所以我写了相应的代码。但我不会因此遇到任何问题。我在我的代码中得到"cout没有命名类型"错误,即使我也包含了适当的头文件和名称空间。请给出你的建议。

#include<iostream>
using namespace std;
struct S {
  virtual void foo();
};
void S::foo() {
  // body for the pure virtual function `S::foo`
 cout<<"I am S::foo()" <<endl;
}
struct D : S {
  cout <<"I am inside D::foo()" <<endl;
};
int main() {
  S *ptr;
  D d;
  ptr=&d;
  //ptr->foo();
  d.S::foo(); // another static call to `S::foo`
  cout <<"Inside main().." <<endl;
  return 0;
}

您试图用直接代码定义结构体,但是看起来您想在代码周围使用方法:

struct D : S {
  cout <<"I am inside D::foo()" <<endl;
};

应该是

struct D : S {
  virtual void foo() {
    cout <<"I am inside D::foo()" <<endl;
  }
};