gpt4 book ai didi

c++ - 为什么我的类(class)不是原型(prototype)?

转载 作者:行者123 更新时间:2023-11-27 23:15:46 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

class Rectangle;


int main(){
Rectangle myRoom(5,10);

cout << myRoom.getHeight() << endl;
cout << myRoom.getLength() << endl;

system("pause");
return 0;
}

class Rectangle{
private:
int height;
int length;

public:
Rectangle(int aHeight, int aLength){
height = aHeight;
length = aLength;
}

int getHeight(){
return height;
}

int getLength(){
return length;
}
};

编译器告诉我 Rectangle、getHeight 和 getLength 未定义。为什么我的类 Rectangle 没有被原型(prototype)化以便我可以在 main 方法下定义它?有人能告诉我我做错了什么吗?谢谢。

最佳答案

这个:

class Rectangle;

是一个前向声明,它基本上只告诉编译器类 Rectangle 存在。由于编译器对此类一无所知,Rectangle 是一个不完整类型

在这一行:

Rectangle myRoom(5,10);

尽管之前未定义类 Rectangle,但您正在尝试创建类 Rectangle 的实例。当然,在这种情况下,前向声明是不够的。 Rectangle 类型仍然不完整。

看看When can I use a forward declaration? ,您会发现其中很好地解释了对于不完整类型可以做什么和不能做什么。

关于c++ - 为什么我的类(class)不是原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16503054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com