【问题标题】:Passing private static array as an argument to public member function in c++?将私有静态数组作为参数传递给c ++中的公共成员函数?
【发布时间】:2015-06-29 10:32:42
【问题描述】:

在线documents 似乎建议将作为参数传递给同一类中的公共函数的类的私有成员变量需要声明为静态。不过,我得到一个编译错误:

class C{

private: 
        static std::string table1[50];

public: 
        bool try (){
            helper(&table1);
            return true; 
        }
        bool helper (std::string * table){
            return true; 
        }

但是我得到这个编译错误:

./c:72:31: error: cannot initialize a parameter of type 'std::string *' (aka
      'basic_string<char, char_traits<char>, allocator<char> > *') with an rvalue of type
      'std::string (*)[50]'

还有什么我错过的吗?

【问题讨论】:

  • 也许你的意思是helper(table1);
  • 你能指出文档吗?我看不出为什么用作参数的私有成员变量需要是静态的。这将是一个严格的限制。
  • 这就是我需要的,它最终工作了:try(){helper(table1)};助手(std::string * table);

标签: c++ function class static pass-by-reference


【解决方案1】:

您的helper 函数将指向std::string 的指针作为参数。您正在向它传递一个指向 50 std::string 数组的指针。相反,传递数组的第一个元素(在这种情况下,数组衰减为指针),如

helper(table1);

helper(&table1[0]);

尽管这就是您所需要的,但我对此表示严重怀疑。指向std::string 的指针在这里看起来有点可疑。最好使用std::vector&lt;std::string&gt;std::array&lt;std::string, 50&gt;

旁注:不要调用您的成员函数try(),因为try 是保留的C++ 关键字。

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2019-09-27
    • 2013-11-21
    • 2020-12-31
    相关资源
    最近更新 更多