【问题标题】:Not Sure how to create object with my class and namespace? c++不确定如何使用我的类和命名空间创建对象? C++
【发布时间】:2013-11-30 21:41:42
【问题描述】:

我编写了一个类大片和命名空间 cs52。创建对象的正确方法是

1) cs52::Blockbuster b(100, “兰博”, “西尔维斯特史泰龙”);

2.)std::Blockbuster b(100, "Rambo", "Sylvester Stallone");

还是有什么不同?

代码:

#include <string>
using namespace std;
namespace cs52 {

class Blockbuster{
public:
Blockbuster( int length, string title, string star );

friend bool equal( const Blockbuster & b1, const Blockbuster & b2 );
int getLength();
string getTitle();
string getPlace();

void setTitle( string title );
void setPlace( string place );
void setLength( int length );

private:
int my_Length; // feature length in minutes
string my_Title; // feature title
string my_Star; // leading actor or actress
};

}

另外,我实际上还没有定义我的 c++ 文件函数。将被实现为 bool Blockbuster::equal(const Blockbuster & b1, const Blockbuster & b2)

或者我需要在声明中的某处包含朋友吗?

【问题讨论】:

  • 删除using namespace std并使用cs52::Blockbuster
  • 当您尝试 1) 和 2) 时发生了什么?
  • 我实际上还没有定义我的 c++ 文件函数。将实现为 bool Blockbuster::equal(const Blockbuster & b1, const Blockbuster & b2) 还是我需要在声明中的某处包含朋友?
  • 在标题中使用命名空间会污染客户端的命名空间。

标签: c++ class object namespaces


【解决方案1】:

using namespace std 不受欢迎(被认为是不好的做法),因为它可能导致conflicts。我建议您删除该行。要实例化您的对象,请使用cs52::Blockbuster。你永远不会在你编写的类上使用std::,因为这是标准库的命名空间。您可能还想添加一些更具体的命名空间指令,例如using std::string。请注意,这是我自己的做事方式,每个人对 C++ 和命名空间都有不同的看法。例如,在头文件中声明命名空间存在一些危险,因为它可能会意外地改变包含它的代码的含义。

回答你的第二个问题:

您只能在声明中使用friend 关键字,而不是在定义/实现中。 (您声明该函数为友元函数)。

【讨论】:

  • 虽然using namespace std; 不是很好的建议,但它与cs52::Blockbuster 对象的实例化方式无关。
  • 他们在询问如何实例化他们的类型。 std 命名空间甚至没有进入它。在他们的两个“替代方案”中,只有第一个可以工作,using namespace std 与否。
  • 如果他们真的尝试过,他们会遇到 2) 的问题。我的观点是,using namespace std; 尽管是一个糟糕的想法,但对于只有 1) 可能起作用这一事实没有任何影响。
  • @juanchopanza 是的,这不仅仅是一个小费。我猜你的意思是我应该解释为什么 cs52 是要走的路。
  • 是的,我的猜测是 OP 觉得他们的类不知何故也在 std 命名空间中,但事实并非如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 2021-12-14
  • 1970-01-01
相关资源
最近更新 更多