[英]Having a class member function call a function outside the class
I have a member function in class B and class D that calls the function 'computeValue' which is not a member function of any class. 我在类B和类D中有一个成员函数,该成员函数调用函数“ computeValue”,这不是任何类的成员函数。 The 'computeValue' function performs some type of algorithm and returns a value. “ computeValue”函数执行某种算法并返回一个值。 However it seems like I'm getting a lot of compilation errors and not sure what the underlying reasons are. 但是,似乎我遇到很多编译错误,并且不确定根本原因是什么。 Is it even possible for member functions of classes to call non-member functions? 类的成员函数甚至可以调用非成员函数吗?
#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
needs the declaration of class A
, so declare A
before it: computeValue
需要类A
的声明,因此在它之前声明A
:
class A
{
};
int computeValue(vector<A*>ex)
{
//implementation of algorithm
}
Is it even possible for member functions of classes to call non-member functions? 类的成员函数甚至可以调用非成员函数吗?
Of cource, yes. 当然,是的。
Yes, definitely you can call class non-member function from class. 是的,绝对可以从类中调用类的非成员函数。
Here you are getting errors because of mainly two issue: 在这里,您主要由于两个问题而收到错误消息:
You are using vector but you haven't declared vector header file in your code. 您正在使用向量,但尚未在代码中声明向量头文件。 #include<vector>
You are using class A pointer as a parameter to function "computeValue" which is defined before the class A. So either define class A before function or use forward declaration concept. 您将使用类A指针作为函数“ computeValue”的参数,该函数在类A之前定义。因此,可以在函数之前定义类A或使用前向声明概念。
Here is error free modified code: 这是无错误的修改代码:
#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;
}
This code will give you output: "D constructor" I hope this will help you. 此代码将为您提供输出:“ D构造函数”,希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.