[英]Having a class member function call a function outside the class
我在類B和類D中有一個成員函數,該成員函數調用函數“ computeValue”,這不是任何類的成員函數。 “ computeValue”函數執行某種算法並返回一個值。 但是,似乎我遇到很多編譯錯誤,並且不確定根本原因是什么。 類的成員函數甚至可以調用非成員函數嗎?
#include<iostream>
using namespace std;
int computeValue(vector<A*>ex) //Error - Use of undeclared identifier 'A'
{
//implementation of algorithm
}
class A
{
};
class B
{
int sam2()
{
return computeValue(exampleB); // Error - No matching function for call to 'computeValue
}
vector <A*> exampleB;
};
class D
{
int sam1 ()
{
return computeValue(exampleD);// Error - No matching function for call to 'computeValue
}
vector<A*> exampleD;
};
int main()
{
}
computeValue
需要類A
的聲明,因此在它之前聲明A
:
class A
{
};
int computeValue(vector<A*>ex)
{
//implementation of algorithm
}
類的成員函數甚至可以調用非成員函數嗎?
當然,是的。
是的,絕對可以從類中調用類的非成員函數。
在這里,您主要由於兩個問題而收到錯誤消息:
您正在使用向量,但尚未在代碼中聲明向量頭文件。 #include<vector>
您將使用類A指針作為函數“ computeValue”的參數,該函數在類A之前定義。因此,可以在函數之前定義類A或使用前向聲明概念。
這是無錯誤的修改代碼:
#include<iostream>
#include<vector>
using namespace std;
**class A; //forward declaration of Class A**
int computeValue(vector<A*> ex) //Error - Use of undeclared identifier 'A'
{
//implementation of algorithm i
return 5;
}
class A
{
};
class B
{
int sam2()
{
return computeValue(exampleB); // Error - No matching function for call to 'computeValue
}
vector <A*> exampleB;
};
class D
{
public:
D()
{
cout<<"D constructor"<<endl;
}
int sam1 ()
{
return computeValue(exampleD);// Error - No matching function for call to 'computeValue
}
vector<A*> exampleD;
};
int main()
{
D d;
}
此代碼將為您提供輸出:“ D構造函數”,希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.