![](/img/trans.png)
[英]How can I initialize a static const vector that is a class member in c++11?
[英]Why can I modify the class with a const function in C++11?
我是CPP的新手,我不知道為什么setValue() const
工作,同時它是一個const。
為什么該類允許從const public
修改
看起來很奇怪,g ++ -Wall或MS Visual C ++沒有錯誤
這是我的代碼:
main.cpp中
#include <iostream>
#include <cassert>
#include "DArray.h"
int main(void)
{
DArray darray(1);
darray.setValue(0, 42);
assert(darray.getValue(0) == 42);
darray.~DArray();
system("pause");
return 0;
}
DArray.h
class DArray
{
private:
int* tab;
public:
DArray();
DArray(unsigned int n);
~DArray();
int& getValue(unsigned int n) const;
void setValue(unsigned int n, int value) const;
};
DArray.cpp
#include "DArray.h"
DArray::DArray()
{
}
DArray::DArray(unsigned int n)
{
tab = new int[n];
}
DArray::~DArray()
{
delete[] tab;
tab = nullptr;
}
int& DArray::getValue(unsigned n) const
{
return tab[n];
}
void DArray::setValue(unsigned n, int value) const // HERE
{
tab[n] = value;
}
這是因為你沒有修改它。 當你這樣做時:
int* tab
選項卡僅包含一個地址。 然后進去
void DArray::setValue(unsigned n, int value) const // HERE
{
tab[n] = value;
}
你沒有修改這個地址,你修改了一些內存。 因此,您不會修改您的課程。
相反,如果你使用了
std::vector<int> tab
你會在setValue中出錯,因為你會修改你的類的元素。
首先,不要明確地調用類的析構函數,當變量自動超出范圍時,將調用它。
darray〜DArray();
你在方法中對const
承諾是不會修改成員變量。 變量int* tab
是指向int的指針。 使用setValue函數,您不會更改指針的地址(承諾不會被方法簽名中的最終const更改),而是指向它指向的int值。 這可以。
但是,如果更改指針地址,例如使用tab = nullptr
,您將看到編譯器錯誤,如:
錯誤:在只讀對象中分配成員'DArray :: tab'
為什么我可以在C ++ 11中使用const函數修改類?
可以修改對象的可變狀態。 技術上也可以使用const_cast
修改非可變狀態,但這樣做是個壞主意,因為如果對象本身是const,那么行為將是未定義的。
然而,這不是你在這段代碼中所做的。
為什么setValue()const同時工作,它是一個const。
因為它不會修改任何this
成員。 它修改了一個指向非const指針的數組。 成員函數的常量或對象的常量不會傳遞給間接指向的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.