我正在尝试在类中定义一个函数,然后在.cpp程序中使用它。我已经将函数声明为main,并且无法弄清楚为什么我在范围错误中未声明。
来自g ++的错误:“错误:'convert'未在此范围内声明”
提前致谢。
啊:
class A
{
public:
int convert(char bcd);
};
program.cpp:
#include "A.h"
#include <iostream>
#include<stdio.h>
using namespace std;
int A::convert(char b)
{
return b*5;
}
int main(){
char myword = '27';
char cc = convert(myword); //scope error here
cout << "Number is: " << cc << endl;
return 0;
}
错误本身是因为您没有任何由名称convert()
定义的“自由函数”,它可以在您尝试调用它的作用域中直接访问。你有一个class A
的成员方法(“函数”),但没有在该类之外定义。所以是的,你有一个名为convert()
的“函数”定义,但它在你试图调用它的范围内是不可访问的。你必须添加一些东西来告诉编译器在哪里找到你想要调用的“convert()
”函数。有几种方法可以做到这一点:
::
范围)解析运算符)来解决范围。::
范围解析运算符(例如“namespaceName::functionName()
”) ,或者使用“using
”关键字将该函数的名称带入当前范围。既然你问的是一个班级成员的方法,我将在下面的讨论中忽略上面的#3 ....
你会有一个class A
的例子吗?如果是这样,说你称之为“fred”,那么你可以打电话给fred.convert(myword);
。但A::convert()
不使用class A
的任何成员数据,所以也许你希望它是一个静态成员方法(即即使没有类的类型的对象也可以调用它),你需要将方法声明为static
,当你打电话给它时,请使用“A::convert(myword);
”。
这是一个创建class A
实例并在其上调用方法A::convert()
的示例:
===== file 'A.h' =====
class A
{
public:
int convert(char bcd);
};
===== file 'program.cpp' =====
#include "A.h"
#include <iostream>
#include<stdio.h>
using namespace std;
int A::convert(char b)
{
return b*5;
}
int main()
{
char myword = '27';
A fred; // create an instance of class A named "fred"
char cc = fred.convert(myword);
cout << "Number is: " << cc << endl;
}
这是一个示例,其中A::convert()
是一个静态成员方法,并且为了调用该方法,不需要该类的实例:
===== file 'A.h' =====
class A
{
public:
static int convert(char bcd); // <--- note 'static' keyword
};
===== file 'program.cpp' =====
#include "A.h"
#include <iostream>
#include<stdio.h>
using namespace std;
int A::convert(char b)
{
return b*5;
}
int main()
{
char myword = '27';
A fred; // create an instance of class A named "fred"
char cc = fred.convert(myword); // you can call convert() on an A object
char dd = A::convert(myword); // or you can call it without an A object
cout << "Number cc is: " << cc << endl;
cout << "Number dd is: " << dd << endl;
}
你混淆了三件事:
函数是一组要在一行中执行的命令。你声明它们是这样的:
type function(type parameter1, type parameter2 /*etc */);
你这样定义它们:
type function(type parameter1, type parameter2 /*etc */) {
// implementation...
}
并称他们为:
type myvar = function(parameter1,parameter2 /*etc */);
Class方法是一个也是类成员的函数。它通常使用实例数据来执行某些操作。你声明他们是这样的:
class A
{
public:
type method(type parameter1, type parameter2);
};
像这样定义它们:
type A::method(type parameter1, type parameter2)
{
return b*5;
}
并称他们为:
A myVar;
myVar.method(parameter1,parameter2);
最后,@ phonetagger建议使用静态类方法。这些类似于常规方法,但通常不接触实例数据。然而,他们通常以某种方式与班级有关。你声明他们是这样的:
class A
{
public:
static type method(type parameter1, type parameter2);
};
像这样定义它们:
type A::method(type parameter1, type parameter2)
{
return b*5;
}
并称他们为:
A::method(parameter1,parameter2);
您需要确定您真正需要哪一个并正确实施。