关于c ++对象创建

Mut*_*thu -4 c++

在以下程序中:

using namespace std;
class c1;
class c2;
int main(int argc,char* argv[])
{
   **c1 obj;
   c2 obj_c2 = obj.method1();**
   return0;
}
class c1
{
public:
  c2 method1()
  {
     c2 obj1;
     return obj1;
  }
};
class c2
{
public:
  int method2()
  {
    return 1;
  }

};
Run Code Online (Sandbox Code Playgroud)

在main函数内部,两行代码给出了错误.我无法编译.

Cat*_*lus 5

您无法定义不完整类型的变量.定义必须在main c2之前可见(c1如果在类中定义成员函数,则在之前):

class c2 {
    // ...
};

class c1 {
    // ...
};

int main() {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

此外,将来,始终在您的问题中包含错误.

  • 可能值得指出你重新排序了`c2`和`c1`的定义. (3认同)