![](/img/trans.png)
[英]How to access the data member of one function into another function inside same class in c++
[英]C++: How to access a class function inside another class?
我正在學習如何使用std :: vector並想訪問其值和函數。 我在另一個稱為光譜的對象中有一個矢量對象。 現在,當我嘗試使用.capacity確定向量的容量時,如果我只是聲明向量,則可以正常工作。 但是,當我在另一個對象中聲明向量時,會出現語法錯誤。
錯誤:
test.c++:36: error: base operand of ‘->’ has non-pointer type ‘Spectrum’
如下面已經提到的,->應該是一個點。
我要確定的是容器的容量,即使它現在可以編譯,它也會給出結果0而不是我期望的結果8。
編碼:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/* spectrum */
class Spectrum{
public:
float oct;
vector<float> band;
float total(){
int k;
float lpow;
// logarithmic summation
for(k = 0; k < oct; k++){
lpow = lpow + pow(10, band[k]);
}
return(10*log10(lpow));
}
Spectrum(int max_oct = 3){
oct = max_oct;
cout << "max oct = " << max_oct << endl;
vector<float> band(max_oct); //create vector/array with max_oct bands
cout << (int)band.capacity() << endl;
}
};
int main()
{
//does not work in a class
Spectrum input(8);
cout << (int)input->band.capacity() << endl;
//does work outside of a class
vector<float> band(8);
cout << (int)band.capacity() << endl;
}
行vector<float> band(max_oct);
不按照您的想法去做。
它在Spectrum構造函數的范圍內定義了一個稱為band
的自動變量。 它不會觸及也稱為band
的成員變量:實際上,它“隱藏”了它,因此以后在構造函數中對band
任何引用都指向自動變量,而不是成員變量(您可以使用this->band
訪問)。
您想要的是:
Spectrum(int max_oct = 3) : oct(max_oct), band(max_oct) {
}
或(較差,因為它構造了一個空向量,然后調整了它的大小,而不是首先構造了正確的大小):
Spectrum(int max_oct = 3) {
oct = max_oct;
band.resize(max_oct);
}
順便說一句,我認為您可能會混淆向量的size
和capacity
(雖然不確定您所說的話)。 vector
的single-arg構造函數創建具有指定大小的向量。 因此,如果尚未安裝,則應將容量設置為8 或更多 ,而不是8。
[編輯:為回答您的下一個問題,您需要在total()
初始化lpow
: float lpow = 0;
]
它不起作用,因為即使輸入不是指針(或具有->
方法的對象),您仍嘗試在輸入上使用->
。 只需使用input.band.capacity
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.