将const放在以下C++语句中的好地方是什么?

rah*_*man 5 c++

考虑以下类成员:

std::vector<sim_mob::Lane *>  IncomingLanes_;
Run Code Online (Sandbox Code Playgroud)

上面的容器应该将指针存储到我的Lane对象中.我不希望子程序使用此变量作为参数,以便能够修改Lane对象.与此同时,我不知道在哪里放'const'关键字不能阻止我填充容器.

你能帮帮我吗?

谢谢你,并感谢vahid

编辑: 根据我到目前为止得到的答案(非常感谢他们所有)假设这个样本:

#include <vector>
#include<iostream>
using namespace std;

class Lane
{
private:
    int a;
public:
    Lane(int h):a(h){}
    void setA(int a_)
    {
        a=a_;
    }
    void printLane()
    {
        std::cout << a << std::endl;
    }
};

class B
{

public:
    vector< Lane const  *> IncomingLanes;
    void addLane(Lane  *l)
    {
        IncomingLanes.push_back(l);
    }

};

int main()
{
    Lane l1(1);
    Lane l2(2);
    B b;
    b.addLane(&l1);
    b.addLane(&l2);
    b.IncomingLanes.at(1)->printLane();
    b.IncomingLanes.at(1)->setA(12);
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

我的意思是:

b.IncomingLanes.at(1) - > printLane()

应该在没有问题的IncomingLanes上工作

b.IncomingLanes.at(1) - >组A(12)

不应该被允许.(在上面的例子中,所提到的两种方法都不起作用!)

除了解决问题之外,我也在寻求良好的编程实践.因此,如果你认为上述问题有一个解决办法,但方法不好,请让我们都知道.Thaks agian

Ton*_*nyK 2

你可以这样做:

std::vector<const sim_mob::Lane *>  IncomingLanes_;
Run Code Online (Sandbox Code Playgroud)

或者这样:

std::vector<sim_mob::Lane const *>  IncomingLanes_;
Run Code Online (Sandbox Code Playgroud)

在 中C/C++,const typename * 和typename const * 的含义相同。

更新以解决更新的问题:

如果你真的需要做的就是

b.IncomingLanes.at(1)->printLane()
Run Code Online (Sandbox Code Playgroud)

那么你只需printLane这样声明:

void printLane() const // Tell compiler that printLane doesn't change this
  {
  std::cout << a << std::endl;
  }
Run Code Online (Sandbox Code Playgroud)