繁体   English   中英

让类成员函数在类外部调用一个函数

[英]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  
}

类的成员函数甚至可以调用非成员函数吗?

当然,是的。

是的,绝对可以从类中调用类的非成员函数。

在这里,您主要由于两个问题而收到错误消息:

  1. 您正在使用向量,但尚未在代码中声明向量头文件。 #include<vector>

  2. 您将使用类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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM