【问题标题】:2 classes with the same name within namespaces命名空间中有 2 个同名的类
【发布时间】:2019-03-01 21:49:45
【问题描述】:

我已经通过一些旧的大学课程重新学习 C++,现在我正在学习参数多态性以及创建自己的命名空间。 练习表明我必须创建一个名为“Federation”的命名空间,它有一个名为“Ship”的类,它接受值和一个永远不会改变的默认值。 在 federation 命名空间内还有一个“Starfleet”命名空间,其中我们还有一个“Ship”类,唯一的区别是前面声明的默认值可以由用户指定。

代码如下:

Federation.hpp

#include <iostream>
#include <string>
#include <cstring>

namespace Federation
{
  namespace Starfleet 
  {
    class Ship
    {
    public:
      Ship(int length, int width, std::string name, short maxWarp);
      ~Ship();
    private:
      int _length;
      int _width;
      std::string _name;
      short _maxWarp;
    };
  };
  class Ship
  {
  public:
    Ship(int length, int width, std::string name);
    ~Ship();
  private:
    int _length;
    int _width;
    std::string _name;
  }
};

Federation.cpp

#include "Federation.hpp"
using namespac std;

Federation::Starfleet::Ship::Ship(int length, int width, string name, short maxWarp): _length(length), _width(width), _name(name), _maxWarp(maxWarp)
{
  cout << "Starfleet Ship Created." << endl;
}

Federation::Starfleet::Ship::~Ship()
{

}

Federation::Ship::Ship(int length, int width, string name, int speed = 1): _length(length), _width(width), _name(name)
{
  cout << "Regular Ship Created"
}

Federation::Ship::~Ship()
{

}

ma​​in.cpp

#include "Federation.hpp"

int main(int ac, char **av)
{
  Federation::Starfleet::Ship mainShip(10, 10, "Starfleet Ship", 20);
  Federation::Ship smallShip(5, 5, "Small Ship");
}

编译时出现此错误:“Federation::Ship::Ship(int, int, std::__cxx11::string, int) 的原型与 Federation::Ship 中的任何类都不匹配”

我完全不知道这意味着什么,当我查看我的 hpp 文件中的函数时,所有这些函数似乎都是正确的,所以我真的不明白在这种情况下我到底做错了什么。

【问题讨论】:

  • 默认参数应该在头文件而不是源文件中定义。将默认参数放在头文件中Federation::Ship构造函数的签名中。
  • 谢谢,成功了!
  • 不是问题,但不要在命名空间后放置;。你不需要它,它可以更容易地发现 } 是关闭命名空间还是关闭类声明
  • ...在类定义之后,您需要 ;,而在第二个 Ship 之后,它就丢失了

标签: c++ class namespaces


【解决方案1】:

这与命名空间无关。您在标头中声明具有特定原型的 c'tor:

Ship(int length, int width, std::string name);

然后在实现文件中随机添加一个带默认参数的参数:

Federation::Ship::Ship(int length, int width, string name, int speed = 1)

参数类型是任何函数或构造函数签名的一部分。所以你有一个声明和定义不匹配。在标头中声明额外参数(连同默认参数)。

Ship(int length, int width, string name, int speed = 1);
// and
Federation::Ship::Ship(int length, int width, string name, int speed)

【讨论】:

  • 一旦我在 main 上声明该类,该类必须默认具有该参数。如果我在原型上添加一个 int speed,我会收到一条错误消息,告诉我构造函数需要另一个参数。
  • @SoftJellyfish - 默认参数必须仅出现在声明中。删除定义中的默认参数(但不是参数)。
猜你喜欢
  • 1970-01-01
  • 2011-12-01
  • 2012-07-31
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 2020-05-02
  • 2011-03-15
  • 1970-01-01
相关资源
最近更新 更多