尽管我包含了iostream,为什么我的类不能识别main.cpp中的iostream类?
所以我正在练习 OOPS 并试图了解私有和公共。为此,我在我的项目的源文件夹中创建了一个不同的文件(顺便说一句,我使用的是 Code::Blocks),如下所示:
+--Sources
+--main.cpp
+--student.cpp
主.cpp :
#include <iostream>
#include "student.cpp"
using namespace std;
int main(){
Student s1;
s1.age = 20;
s1.rollNo = 101;
s1.display();
}
学生.cpp:
class Student{
public:
int rollNo;
private:
int age;
public:
void display(){
cout << age << " " << rollNo << endl;
}
};
编辑 student.cpp :
#include <iostream>
class Student{
public:
int rollNo;
private:
int age;
public:
void display(){
std::cout << age << " " << rollNo << std::endl;
}
};
这给了我以下错误:
error: 'endl' was not declared in this scope
error: 'cout' was not declared in this scope
error: 'int Student::age' is private within this context
据我了解,前两个错误是由于 student.cpp 无法识别 iostream 标头。是否有不同的方式来处理 code::blocks 中的类,如果没有,我还能使用什么?
另外,为什么我会收到第三个错误,因为我试图age使用类中display公开的不同函数()进行访问Student?
回答
此代码的组织有太多问题导致您遇到问题。这是要解决的问题的列表:
- 永远不要使用赤裸裸的
using namespace std;(在明确定义的范围之外)。“全局”使用它(就像您所做的那样)通过改变远处代码的含义来破坏封装(在某种意义上)。令人费解的行为只是后果之一。 cpp文件永远不会#included.cpps 用于实现,hpps 用于声明(可能还有一些实现)。- 你的
student.cpp文件应该是一个student.hpp真正的 student.hpp应该有自己的“头”依赖(#include<iostream>instudent.hpp)- 说
std::cout和std::endl,或using std::cout; using std::endl;(最坏的情况using namespace std)但在本地。
以上都是关于风格和惯例的。除此之外,您还有语法错误:
age应该根据main.- 从评论看来,您想保护类的某些内部结构(例如年龄),在这种情况下,您需要将它们设为私有,而不是从 main 访问它们,并为该类设置一个公共构造函数。
理想情况下,您的代码应如下所示(未经测试):
+--Sources
+--main.cpp
+--student.hpp
主.cpp :
#include "student.hpp"
using namespace std;
int main(){
Student s1;
s1.age = 20;
s1.rollNo = 101;
s1.display();
}
学生.hpp:
#include <iostream>
class Student{
public:
int rollNo;
int age;
private:
// was int age
public:
void display(){
using std::cout;
cout<< age <<" "<< rollNo <<'n'; // no need for endl
}
};
student.cpp 不需要或可能为空。
- 问题中的第三个错误是您将“年龄”设为私有。你不能从课堂外访问它。所以在 `int main()` 中尝试 `s1.age = 20;` 是无效的,编译器是正确的。
THE END
二维码