【问题标题】:How to access the arrays in private class of C++?如何访问 C++ 私有类中的数组?
【发布时间】:2017-12-15 07:55:48
【问题描述】:
class bus {

private:    
    string arr[10] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

public:     
    void reservation();

};

在这里,我有一个私有数组,我想通过 public 类中的 reservation() 访问并进行更改。

void bus::reservaton() {

cout << "What should I write in here to change the 3rd and 7th index of the 
above array to \"not empty\"" << endl;

}

假设,我想让第 3 和第 7 个索引为“不为空”,我应该在那里写什么?

示例:-

string arr[10] = { "0", "1", "2", "not empty", "4", "5", "6", "not empty", "8", "9" };

我需要对主函数进行任何更改吗?如果是,那么请您帮我写下来。 谢谢。

【问题讨论】:

  • arr[3] = "not empty"?
  • 成员函数可以访问私有成员,否则两者都将毫无用处
  • 此时最好的做法是阅读一本书或至少阅读 C++ 教程。说真的。
  • 你的私教课在哪里?

标签: c++ arrays class c++11 private


【解决方案1】:

为此,一个简单的assignment operator (=) 就可以了。

例如,在以下示例中,索引1 处的值已更改:

std::string slist[ 3 ] { "a", "b", "c" }; 
slist[ 1 ] = "Changed!";

现场示例:http://ideone.com/rO9hwt

顺便说一句,您应该使用std::string 中的std::vector 而不是数组。并且,看看它的成员函数at() 来访问一个索引的值并检查out of bounds

现场示例:http://ideone.com/bcHZpY

【讨论】:

    【解决方案2】:

    How to use arrays

    void bus::reservation() {
      arr[3] = "not empty";
      arr[7] = "not empty";
    }
    

    【讨论】:

    • 它是语法糖,完整的语法是“ this.arr[3] = "not empty"; "
    • @RomanGrout 将“full”替换为“wrong”,您的评论是正确的:P this 是一个指针,this.arr 将不起作用。无论如何在会员面前写this-&gt;纯属个人喜好
    • @tobi303 不要那么苛刻......还有一点需要注意的是,this-&gt; 不仅仅是一个品味问题 :)
    • @W.F.该评论并不意味着苛刻。只是想确保错误信息得到纠正。并感谢您指出我的错误信息;)
    猜你喜欢
    • 2013-06-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2013-05-25
    相关资源
    最近更新 更多