【发布时间】:2012-02-18 06:42:39
【问题描述】:
我已经用 C# 编程几年了,因为它是我的第一语言。我正在努力复习我的 C++,因为我很快就会着手编写一些用 C++ 编写的代码。
这段代码有什么问题:(我知道可能有很多问题。C++ 与 C# 的需求大不相同)。有人告诉我,我不知道如何在 C++ 中正确声明类,并且我需要使用头文件来定义我的类。我需要标题吗?这是一个小程序,只是为了测试,想知道没有它是否可以完成。缺少的标题是这里唯一的问题吗?我有一个关于无法在 Company 中访问 Parse 的错误,但是当我在 Company 类名前面添加 public 时,它会引发更多错误。
啊!好郁闷。
#include "std_lib_facilities.h"
using namespace std;
class Employee
{
public:
string screen_name;
string real_name;
string current_job;
int employee_number;
Employee(int no, string name1, string name2, string current_jobin)
{
screen_name=name1;
real_name=name2;
employee_number=no;
current_job=current_jobin;
}
};
class Project
{
public:
Vector<Employee> Employees;
int max_worker_quota;
int project_id;
string project_name;
Project(int no_in,int max_in,string title_in)
{
max_worker_quota=max_in;
project_name=title_in;
project_id=no_in;
}
};
unsigned int split(const std::string &txt, vector<std::string> &strs, char ch)
{
unsigned int pos = txt.find( ch );
unsigned int initialPos = 0;
strs.clear();
// Decompose statement
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos + 1 ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
// Add the last one
strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1));
return strs.size();
}
class Company
{
Vector<Employee> Employeelist;
Vector<Project> Projectlist;
void Parse(string input)
{
//Case Statements
vector<string> temp;
split( input, temp, ' ' );
if (temp[0]=="S")
{
//Add Employee to Company
Employee myEmployee=Employee(atoi(temp[1].c_str()),temp[2],temp[3],temp[4]);
Employeelist.push_back(myEmployee);
}
else if (temp[0]=="C")
{
//Add Project to Company
Project myProject=Project(atoi(temp[1].c_str()),atoi(temp[2].c_str()),temp[3]);
Projectlist.push_back(myProject);
}
else if (temp[0]=="L")
{
//Add Employee to Project list
//Not Implemented-Find Project by temp[1] which is a int
}
else if (temp[0]=="A")
{
}
else if (temp[0]=="D")
{
}
else if (temp[0]=="PS")
{
}
else if (temp[0]=="PC")
{
}
}
};
int main(int argc, char *argv[])
{
string input;
cout<<"Command:: ";
cin>>input;
Company myCompany;
myCompany.Parse(input); //Input is in the format X Name Name etc etc. Arguments separated by spaces
return 0;
}
【问题讨论】:
-
C++ 不关心标题,它关心翻译单元。
-
有什么错误?你使用的那个标题,是 Bjarne Stroustrup 书中的那个吗? This one?
-
您遇到了什么错误?
-
如果将所有代码放在一个文件中,则不需要 标头。但是你确实需要正确缩进你的代码。请。
-
是的。标题来自他的书。好发现!!我现在遇到的错误是 Parse 无法访问的问题。我也简单地为该方法添加了一个公共,它现在可以工作了。但我主要担心的问题是我的一个朋友说我在宣布我的课程完全错误。我需要单独的标题来管理所有内容。仍然对那部分感到困惑。看起来像是编译的,所以我实际上并不需要它们,而是根据其他人做。将尝试对此进行更多研究。
标签: c++ class header compiler-errors private-members