gpt4 book ai didi

c++ : Receiving a lot of errors. 简单继承导致大量错误

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:12 27 4
gpt4 key购买 nike

下面是我的 3 个 cpp 文件和 2 个头文件。我收到了天文数字的错误,而且大多数都非常不清楚。我是 C++ 的新手并且有 C#/Java 背景。

我很清楚以下可能是语法错误。提前感谢您的帮助。

主要.cpp:

#include <iostream>
#include "B.h"
#include "S.h"

using namespace std;

int main() {
B b;
S s("Jon");
return 0;
};

B.h:

#ifndef B_H
#define B_H

class B {
public:
B();
};

#endif

B.cpp:

#include <iostream>
#include <string>
#include "B.h"
#include "S.h"

using namespace std;

class B {
public:
B() {}
};

S.h:

#ifndef S_H
#define S_H

class S: public B {
public:
S(string name);
}
#endif

S.cpp:

#include <iostream>
#include <string>
#include "B.h"
#include "S.h"

using namespace std;

class S: public B {

private:
string s;

public:
S(string name) {
s = name;
}
};

这是我的一大堆错误 list 。这有点让人不知所措。

enter image description here

最佳答案

1) 你不能在头文件中定义一个类,然后在一些源文件中重新定义它。

类的(前向)声明是这样的声明:

class X;

一个类的定义是这样的:

class X
{
// stuff
};

这样的定义对于每个类只能出现一次。

如果您不想让数据成员成为您公共(public)接口(interface)的一部分,您可以

  1. 使用opague pointer将它们完全隐藏在标题中或
  2. 将这些成员设为私有(private)。

B.h

#indef B_H
#define B_H
#include <string> // to be used here, so we need to include it
// not "using namespace std;" here!! *
class B
{
public:
B();
void setValues();
std::string printValues() const; // don't miss that std::
private:
std::string s, result;
float f;
int i;
bool b;
};
#endif

B.cc

#include "B.h"

B::B()
: f(), i(), b() // **
{ }

void B::setValues() { }

std::string printValues() const
{
result = s + " " + std::to_string(i) + " " +
std::to_string(f) + " " + std::to_string(b);
return result;
}

S.h

#ifndef S_H
#define S_H
#include "B.h" // required to make B known here
#include <string> // known through B, but better safe than sorry
class S : public B
{
public:
S(std::string name);
std::string subPrint() const; // ***
};
#endif

S.cc

#include "S.h"

S::S(std::string name)
: s{name} // **
{ }

std::string subPrint () const // ***
{
return printValues() + s;
}

*: Why is “using namespace std” in C++ considered bad practice?

**: C++, What does the colon after a constructor mean?

***: Meaning of “const” last in a C++ method declaration?

2) 您必须在使用类型的所有地方包含所需的 header 。

您的 B.h 不包括但使用 string 我怀疑是指 std::string

关于c++ : Receiving a lot of errors. 简单继承导致大量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682949/

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