似乎有個說法,盡可能的在引數前加const,防止引數變化,我想對陣列求和,引數是陣列起始地址和結束地址,這兩個地址(指標)在函式中是常量,但如何加上呢?下面是我寫的程式
#include<iostream>
using namespace std;
const int ArSize = 8;
int sum_arr1(const int &begin,const int &end);
int sum_arr2(const int* begin,const int* end);
int main()
{
int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
int sum_1= sum_arr1(cookies[0], cookies[8]);
int sum_2 = sum_arr2(cookies, cookies+8);
cout << sum_1 << endl;
cout << sum_2 << endl;
return 0;
}
int sum_arr1(const int &begin,const int &end)
{
int* pt;
int total = 0;
for (pt = &begin; pt != &end; pt++)
total = total + *pt;
return total;
}
int sum_arr2(int* const begin, int* const end)
{
int* pt;
int total = 0;
for (pt = begin; pt != end; pt++)
total = total + *pt;
return total;
}
uj5u.com熱心網友回復:
#include<iostream>
using namespace std;
const int ArSize = 8;
int sum_arr2(const int* begin, const int* end);
int main()
{
int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
int sum_2 = sum_arr2(cookies, cookies + 8);
cout << sum_2 << endl;
return 0;
}
int sum_arr2(const int* begin,const int* end)
{
const int* pt;
int total = 0;
for (pt = begin; pt != end; pt++)
total = total + *pt;
return total;
}
對于常量指標和指標常量的區別,請參考《C++中指向常量的指標和常量指標》
希望能夠幫到您!
uj5u.com熱心網友回復:
const int * const,第一個 const 修飾 int,第二個 const 修飾指標。意為:指向整型常量的常量指標uj5u.com熱心網友回復:
常整型 的指標 的常量A的常量,即A本身是常量
B的指標,即指標指向的類容其型別是B型別
常整型的指標,即 指標 指向的內容其型別是一個常幀型的。【一個指向了整數且是常數的指標】
常整型 的指標 的常量,即 指標【指向的內容其型別是一個常幀型的】,并且其是常量
const * const <=>常量 指標 常量
uj5u.com熱心網友回復:
const對指標有兩種加法,一直是指標本身是const,一種是指標指向的值是constuj5u.com熱心網友回復:
因為你在函式內部都先用一個非const的int*去參考資料 所以你的引數是否加const 關系不大(你的函式內部應該需要強制型別轉換)你可以直接用
const int sum(const int* pbegin, const int* pend){
int i = 0;
while (pbegin != pend)
i += *pbegin++;
}
之類的
實際上 c++已經內置類似功能了 比如c++20可以這么寫:
#include <iostream>
#include <algorithm>
#include <numeric>
int main()
{
const int x[]{1,2,3,4};
std::cout
<< std::accumulate(std::begin(x), std::end(x), 0)
<< std::endl;
}
在我的機器上 Cygwin下用
g++ sum.cc --std=c++2a
是可以正常作業的
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/9534.html
標籤:C++ 語言
上一篇:c++
